Python calls each other with A/C + + module
Python calls c dynamic-link library
Python's call to C library is simple, packaged into so without any encapsulation, and then using Python's ctypes call.
<test.cpp Generating source files for dynamic libraries >
- #include <stdio.h>
- extern "C" {
- void display () {
- printf ("This is Display function\n");
- }
- }
- g++ Test.cpp-fpic-shared-o libtest.so
<call.py calling the source file of the dynamic library >
- Import cTYPES
- so = cTYPES. Cdll ("./libtest.so")
- So.display ()
It is important to note that when you use g++ to compile a function or method in a code that generates a dynamic library, you need to use extern "C" to compile
Python calls C + + (with class, overloaded) dynamic-link libraries
But call C + + so is a bit of a hassle, the Internet to find the next, most of the need for extern "C" to assist, that is, can only call C function can not call the method directly but can parse C + + method.
<test.cpp Generating source files for dynamic libraries >
- #include <Akita/Akita.h>
- class testlib{
- Public:
- void display ();
- void display (int a);
- };
- void TestLib::d isplay () {
- cout<<"First display"<<endl;
- }
- void TestLib::d isplay (int a) {
- cout<<"Second display"<<endl;
- }
- extern "C" {
- TestLib obj;
- void display () {
- Obj.display ();
- }
- void Display_int () {
- Obj.display (2);
- }
- }
g++ Test.cpp-fpic-shared-o libtest.so
Using this method is a bit of a hassle but can solve the problem. Notice that there will still be an extern "C" or the built-in dynamic link library does not have the symbolic table of these functions.
<call.py calling the source file of the dynamic library >
- Import cTYPES
- so = cTYPES. Cdll ("./libtest.so")
- So.display ()
- So.display_int (1)
The results of the operation are as follows:
- ^[[email Protected]:~/projects/nugget/kvdb-py] #python call.py
- First display
- Second Display
C + + Call Python module
<test.cpp >
- #include <Akita/Akita.h>
- #include <Python.h>
- int Main () {
- Py_initialize ();
- if (! Py_isinitialized ()) return FALSE;
- Pyrun_simplestring ("Import sys");
- Pyrun_simplestring ("sys.path.append ('./')");
- //import Module
- pyobject* pmodule = pyimport_importmodule ("Hello");
- if (!pmodule) {
- cout<<"Can ' t import module!/n"<<endl;
- 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 ();
- return 0;
- }
#g + + test.cpp-i/usr/local/include/python2.7-ldl-lutil-lpthread-lpython2.7
<call.py>
- def Display (name):
- Print "HI", name
———
C + + writes extension modules for Python
Python provides scripting interfaces for C + +.
The interaction between the two is very convenient.
From:blog.csdn.net/crazyjixiang Crazyjixiang
Python mixed programming with C + +