This article describes how to use python scripts to access and write c ++ modules without compiling c ++ programs as a dynamic library, the following is a detailed description of the relevant content.
There is an application in the project at hand. You need to embed a python script in a program written in c ++, use the python script for some computation, and return the value to the c ++ Host Program. Python script computation must be provided by c ++. It is not convenient for python to access the Host Program, the methods provided on the Internet are to use python to write socket or share memory to communicate with the c ++ program, which is obviously not very convenient here.
A good idea is to program a part of the code that accesses internal data in c ++ into a python build-in module, let the python script introduce this module to communicate with c ++. However, the problem is that python only provides examples and tutorials for compiling dynamic library loading by embedding the c ++ module. The dynamic library cannot directly access the variables of the c ++ program.
The solution to this problem is to directly use the python module code written in c ++ as part of the entire program project, and actively call the python interpreter in the main program to load the module, the dynamic library link is skipped. This part of the code is a part of the program and can directly access the program variables.
The c ++ code for actively loading a module is as follows:
- Py_InitializeEx(0);
Initialize Interpreter
- Py_InitModule("ModuleName", ModuleMethods);
ModuleMethonds is an array of interfaces defined in the python module written in c ++. The type is
- PyMethodDef []
For details about how to compile the module, refer to the python manual. Note that the module is divided into cpp and. H files, so that the main program references the header file, so that the main program can access the ModuleMethods array. The above is an introduction to the content related to the mutual call DE Of The Python script embedded in the C ++ application and the C ++ program. I hope you will gain some benefits.