The last time I wrote a command to encapsulate and call C functions using the APIS provided by python. However, because the method of using APIS is too primitive, it is extremely troublesome for classes or structures. Therefore, I chose boost python to encapsulate classes, and similar tools include swig. The reason why I chose boost is that it does not need to introduce other Interface Description Languages, encapsulation is also C ++ Code. In addition, it supports a wide range of C ++ features.
Boost Python documentation, I recommend: http://www.maycode.com/boostdoc/boost-doc/libs/python/doc /. Basically, you can find the answer to your questions.
The following is an example, which covers a wide range of areas and needs to be well understood. This example shows how to encapsulate C ++. In the next section, I will 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: Python;
- Namespace hellopython {
- // Simple functions
- Char const * sayhello (){
- Return "hello from boost: Python ";
- }
- // Simple class
- Class helloclass {
- Public:
- Helloclass (const string & name): Name (name ){
- }
- Public:
- String sayhello (){
- Return "hello from helloclass by:" + name;
- }
- PRIVATE:
- String name;
- };
- // Accept simple functions of this class
- String sayhelloclass (helloclass & Hello ){
- Return hello. sayhello () + "in function sayhelloclass ";
- }
- // STL container
- Typedef vector <int> ivector;
- // Functions with default parameter values
- Void showperson (string name, int age = 30, string nationality = "China "){
- Cout <name <"" <age <"" <nationality <Endl;
- }
- // Encapsulate functions with default parameter values
- Boost_python_function_overloads (showperson_overloads, showperson, 1, 3) // 1: Minimum number of parameters and maximum number of three parameters
- // Encapsulation Module
- Boost_python_module (hellopython ){
- // Encapsulate simple functions
- Def ("sayhello", sayhello );
- // Encapsulate simple classes and define the _ init _ Function
- Class _ ("helloclass", INIT ())
- . Def ("sayhello", & helloclass: sayhello) // Add a regular member function
- ;
- Def ("sayhelloclass", sayhelloclass); // sayhelloclass can be made a member of module !!!
- // Simple STL Encapsulation Method
- Class _ ("ivector ")
- . Def (vector_indexing_suite ());
- Class _> ("ivector_vector ")
- . Def (vector_indexing_suite> ());
- // Encapsulation method with default parameter values
- Def ("showperson", showperson, showperson_overloads ());
- }
Series of articles:
Python calls C/C ++ functions (1)
Python calls C ++ (2) encapsulated by boost Python)
C ++ calls Python (3)
C ++ calls Python (4)
C ++ and Python advanced application interoperability (5)