Last time I wrote a C function using the API provided by Python, and called. But because the way the API is used is too primitive, it is extremely troublesome for a class or structure. So, I chose boost python to encapsulate the class, similar tools, swig, and so on, because it does not need to introduce other interface Description language, encapsulation is C + + code, in addition, it supports the C + + characteristics of the whole.
Boost Python's documentation, I recommend: http://www.maycode.com/boostdoc/boost-doc/libs/python/doc/. Basically, you can find the answer to the problem you are having.
Here is an example, this example covers a full face, need to understand. This example is a study of how to encapsulate C + +. In the next section, I'll write some advanced usage.
#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::p Ython;
Namespace hellopython{//Simple function char const* SayHello () {return "Hello from boost::p Ython"; }//Simple classes Class helloclass{Public:helloclass (const string& name): Name (name) {} public:string say
Hello () {return "Hello from Helloclass by:" + name;
} private:string name;
};
Accept the simple function of the class string Sayhelloclass (helloclass& Hello) {return Hello.sayhello () + ' in function Sayhelloclass ';
//STL container typedef vector<int> Ivector; function void Showperson with default parameter value (String name,int age=30,string nationality= "I") {cout << name << "" <
< age << "" << nationality << Endl; }//encapsulates a function with default parameter values Boost_python_function_overloads (showperson_overloads,showperson,1,3)//1: Minimum number of parameters, 3 maximum parameters//Encapsulation Module Boost_python_module (Hellopython) {//encapsulation simple function def ("SayHello", SayHello); Encapsulates a simple class and defines the __init__ function Class_ ("Helloclass", Init ()). def ("SayHello", &helloclass::sayhello)//add a regular mem
ber function; def ("Sayhelloclass", Sayhelloclass);
Sayhelloclass can is made a member of module!!!
The simple encapsulation method of STL Class_ ("Ivector"). Def (Vector_indexing_suite ());
Class_ > ("Ivector_vector"). Def (Vector_indexing_suite > ());
Package method def with default parameter values ("Showperson", Showperson,showperson_overloads ()); }