Python and c/c ++ Mixed Programming
Python and C/C ++ modules call each other
Python calls C Dynamic Link Library
It is very easy for Python to call the C library. It can be called using python's ctypes without packaging it into so.
# Include
Extern"C "{
VoidDisplay () {printf ("This is Display Function \ n");} g ++ test. cpp-fPIC-shared-o libtest. so
ImportCtypesso = ctypes. CDLL ("./libtest. so") so. display ()
Note: When using g ++ to compile functions or methods in the code of the dynamic library, use extern "C" for compilation.
Python calls the C ++ (including classes and overloading) Dynamic Link Library
However, Calling C ++'s so is a little troublesome. Most of the requests on the internet need to be assisted by extern "C, that is to say, only C functions can be called. methods cannot be called directly, but C ++ methods can be parsed.
# Include
ClassTestLib {
Public:
VoidDisplay ();
VoidDisplay (
IntA );
};
VoidTestLib: display () {cout <"First display" <
VoidTestLib: display (
IntA) {cout <"Second display" < Extern "C" {TestLib obj;
VoidDisplay () {obj. display ();}
VoidDisplay_int () {obj. display (2 );}}
G ++ test. cpp-fPIC-shared-o libtest. so
This method is troublesome but can solve the problem. Note that there will still be an extern "C" later. Otherwise, the constructed dynamic link library does not have the symbol tables of these functions.
ImportCtypesso = ctypes. CDLL ("./libtest. so") so. display () so. display_int (1)
The running result is as follows:
^ [Root @:~ /Projects/nugget/kvDB-py] # python call. pyFirst displaySecond display
C/C ++ calls the Python Module
# Include
IntMain () {Py_Initialize ();
If(! Py_IsInitialized ())
ReturnFALSE; PyRun_SimpleString ("import sys"); PyRun_SimpleString ("sys. path. append ('./')");
// Import Module PyObject * pModule = PyImport_ImportModule ("hello ");
If(! PModule) {cout <"Can't import Module! /N "< Return-1 ;}
PyObject * pDict = PyModule_GetDict (pModule );
If(! PDict ){
Return-1 ;}
// Fetch Function PyObject * pFunHi = PyDict_GetItemString (pDict, "display"); PyObject_CallFunction (pFunHi, "s", "Crazybaby"); Py_DECREF (pFunHi );
// Release Py_DECREF (pModule); Py_Finalize ();
Return0 ;}
# G ++ test. cpp-I/usr/local/include/python2.7-ldl-lutil-lpthread-lpython2.7
DefDisplay (name ):
Print"Hi", name
---
C ++ programming extension modules for Python
Python provides a script interface for C ++.
With the ease of interaction between the two.