Home > Article > Backend Development > How to use c++ code in python
Everyone knows that the advantages of Python are high development efficiency and ease of use, while C has high operating efficiency. The two can complement each other, whether it is embedding C code in a Python project, or using Python to implement peripherals in a C project Functions, you may encounter the need for Python to call C modules.
#The following is a list of methods for exporting centralized C code into a Python interface. Let's learn together.
Original Export (Recommended learning: Python video tutorial)
The Python interpreter is implemented in C, so As long as our C data structure can be understood by Python, it can theoretically be called directly. We implement test1.cpp as follows
#include <Python.h> int Add(int x, int y) { return x + y; } int Del(int x, int y) { return x - y; } PyObject* WrappAdd(PyObject* self, PyObject* args) { int x, y; if (!PyArg_ParseTuple(args, "ii", &x, &y)) { return NULL; } return Py_BuildValue("i", Add(x, y)); } PyObject* WrappDel(PyObject* self, PyObject* args) { int x, y; if (!PyArg_ParseTuple(args, "ii", &x, &y)) { return NULL; } return Py_BuildValue("i", Del(x, y)); } static PyMethodDef test_methods[] = { {"Add", WrappAdd, METH_VARARGS, "something"}, {"Del", WrappDel, METH_VARARGS, "something"}, {NULL, NULL} }; extern "C" void inittest1() { Py_InitModule("test1", test_methods); }
The compilation command is as follows
g++ -fPIC -shared test1.cpp -I/usr/include/python2.7 -o test1.so
-fPIC: Generate position-independent target code, suitable for dynamic connection;
- L path: means searching for library files in the path directory, such as -L. means searching in the current directory;
-I path: means searching for header files in the path directory;
-o file: specifies the output file as file;
-shared: Generate a shared library file;
Run the Python interpreter and test as follows
>>> import test1 >>> test1.Add(1,2) 3
There are a few points to note here
If the name of the generated dynamic library is test1, the source file must have the inittest1 function, and the first parameter of Py_InitModule must be "test1", otherwise the Python import module will fail
If it is a cpp source file, the inittest1 function must be modified with extern "C". If it is a c source file, it is not required. The reason is that the Python interpreter will look for functions such as initxxx when importing libraries, and C and C encode function symbols differently. C will consider the function length and parameter type when encoding function symbols. Specifically, you can pass nm test1. So check the function symbols, and the c filt tool can decode the function prototype through the symbols.
For more Python related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to use c++ code in python. For more information, please follow other related articles on the PHP Chinese website!