Python 调用 C++

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#include <boost/python.hpp>
#include <boost/python/module.hpp>
 
#include <boost/python/def.hpp>
#include <boost/python/to_python_converter.hpp>
#include
using namespace std;
using namespace boost::python;
 
namespace HelloPython{
// 简单函数
char const* sayHello(){
    return "Hello from boost::python";
}
 
 
// 简单类
class HelloClass{
public:
    HelloClass(const string& name):name(name){
    }
public:
    string sayHello(){
      return "Hello from HelloClass by : " + name;
    }
private:
    string name;
};
// 接受该类的简单函数
string sayHelloClass(HelloClass& hello){
    return hello.sayHello() + " in function sayHelloClass";
}
 
 
//STL容器
typedef vector<int> ivector;
 
 
//有默认参数值的函数
void showPerson(string name,int age=30,string nationality="China"){
    cout << name << " " << age << " " << nationality << endl;
}
 
// 封装带有默认参数值的函数
BOOST_PYTHON_FUNCTION_OVERLOADS(showPerson_overloads,showPerson,1,3) //1:最少参数个数,3最大参数个数
 
// 封装模块
BOOST_PYTHON_MODULE(HelloPython){
    // 封装简单函数
    def("sayHello",sayHello);
 
    // 封装简单类,并定义__init__函数
    class_("HelloClass",init())
      .def("sayHello",&HelloClass::sayHello)//Add a regular member function
      ;
    def("sayHelloClass",sayHelloClass); // sayHelloClass can be made a member of module!!!
 
    // STL的简单封装方法
    class_("ivector")
      .def(vector_indexing_suite());
    class_ >("ivector_vector")
      .def(vector_indexing_suite >());
 
    // 带有默认参数值的封装方法
    def("showPerson",showPerson,showPerson_overloads());
}