Python has high development efficiency and low operation efficiency. C/C ++ is the opposite. Therefore, it is necessary to call the C/C ++ library in the Python script to expand python. Http://www.python.org/doc/ using Python APIs
To install Python-Dev.
The test. cpp file is as follows:
# Include <python2.6/python. h> // contains the python header file <br/> // 1 C/CPP function <br/> int my_c_function (const char * Arg) {<br/> int n = System (ARG); <br/> return N; <br/>}< br/> // 2 Python packaging <br/> static pyobject * wrap_my_c_fun (pyobject * Self, pyobject * ARGs) {<br/> const char * command; <br/> int N; <br/> If (! Pyarg_parsetuple (ARGs, "S", & command) // converts the ARGs variable of python to the variable command of C. <br/> return NULL; <br/> N = my_c_function (command); // call the C function <br/> return py_buildvalue ("I", N ); // convert the return value n of C to a python object <br/>}< br/> // 3 method list <br/> static pymethoddef mycppmethods [] = {<br/> // mycppfun1 is the name of the function registered in Python, wrap_my_c_fun is a function pointer <br/> {"mycppfun1", wrap_my_c_fun, meth_varargs, "execute a shell command. "},< br/> {null, null, 0, null} <br/> }; <br/> // 4 module initialization method <br/> pymodinit_func initmycppmodule (void) {<br/> // initial module, initialize mycppmethods to mycppmodule <br/> pyobject * m = py_initmodule ("mycppmodule", mycppmethods); <br/> If (M = NULL) <br/> return; <br/>}< br/>
Make:
G ++-shared-FPIC test. cpp-O mycppmodule. So
After compilation, the directory contains a mycppmodule. So file.
The test. py file is as follows:
#-*-Coding: UTF-8-*-<br/> Import mycppmodule <br/> # import the python module (that is, the C Module, note that the so file name is mycppmodule <br/> r = mycppmodule. mycppfun1 ("ls-L") <br/> Print r <br/> Print "OK"
Run
LHB @ localhost :~ /Maplib/cLib/PyC/invokec $ Python test. py
Total 20
-Rwxr-XR-x 1 LHB 45 2010-08-11 :45 make
-Rwxr-XR-x 1 LHB 7361 2010-08-12 mycppmodule. So
-RW-r -- 1 LHB 979 2010-08-11 test. cpp
-RW-r -- 1 LHB 181 2010-08-11 test. py
0
OK
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)