Python 調用 C++
#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());
}</pre>