In fact, there are two methods for C ++ to call Python: Find Python modules, classes, methods, and constructor parameters. The second method is to construct a Python script and run it using the python engine. The first method may be more elegant and meets the characteristics of most reflection calls. (In a previous project, I implemented the reflection mechanism of C #. C # Calls COM + and C # Calls JavaScript scripts ).
Another problem is that when two languages call each other, they need to convert data structures (such as basic types, strings, integers, and custom classes, an object in the shared memory. For example, how to import a C ++ object instance to Python and use it in Python. C ++ and Python are not in one process, so they can be implemented using shared_ptr of boost.
The following example demonstrates that C ++ can generate a Python script in C ++ and then use pyrun_simplestring to call python, construct a C ++ object, pass it into python, and call its function in the Python script.
- # Include <boost/python. HPP>
- # Include <iostream>
- Using namespace boost: Python;
- Class world
- {
- Public:
- Void set (STD: String MSG) {This-> MSG = MSG ;}
- STD: String greet () {return MSG ;}
- STD: String MSG;
- };
- Typedef boost: shared_ptr <world> world_ptr;
- Boost_python_module (Hello)
- {
- Class _ <world> ("world ")
- . Def ("Greet", & World: Greet)
- . Def ("set", & World: Set)
- ;
- Register_ptr_to_python <world_ptr> ();
- }
- Int main (INT argc, char * argv [])
- {
- Py_initialize ();
- World_ptr worldobjectptr (New World );
- Worldobjectptr-> set ("hello from C ++! ");
- Try
- {
- Inithello ();
- Pyrun_simplestring ("Import hello ");
- Object Module (handle <> (borrowed (pyimport_addmodule ("_ main __"))));
- Object dictionary = module. ATTR ("_ dict __");
- Dictionary ["pyworldobjectptr"] = worldobjectptr;
- Pyrun_simplestring ("pyworldobjectptr. Set ('Hello from python! ')");
- }
- Catch (error_already_set)
- {
- Pyerr_print ();
- }
- STD: cout <"worldobjectptr-> greet ():" <worldobjectptr-> greet () <STD: Endl;
- Py_finalize ();
- Return 0;
- }
-
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)