If you want to better understand the functions of Python when embedding C/C + in practical applications, you can browse our article to have a deep understanding of Python embedding C/C +. The following is a detailed description of the article, and I hope you will gain some benefits.
Python embedded in C/C +
Embedding Python in C/C ++ can use the powerful functions provided by Python. Embedding Python can replace interfaces in the form of dynamic link libraries, so that you can easily modify script code as needed, instead of re-compiling the dynamic link library of the link binary.
Python can be embedded at a high level using Python/C APIs. The so-called high-level embedding mainly refers to the absence of interaction between programs and scripts. Create a blank "Win32 Console Application" in VC ++ 6.0 and a new C source file in the project. Add the following code to it.
- #include <Python.h>int main(){ Py_Initialize(); /*
Python interpreter Initialization
- */ PyRun_SimpleString("print 'hi,python!'"); /*
Run the string */Py_Finalize ();/* to end the Python interpreter and release the resource.
- */ return 0;}
To embed Python into C/C +, You need to compile the project. After running the program, the output is as follows.
- hi,python!
We can see that the program is very simple and only three functions are used. The prototype of the Py_Initialize function is as follows.
- void Py_Initialize()
You must use this function when embedding a Python script. It initializes the Python interpreter. You must call the Py_Initialize function before using other Python/C APIs. The PyRun_SimpleString function is used to execute a piece of Python code. The function prototype is as follows.
- int PyRun_SimpleString(const char *command)
The Py_Finalize function is used at the end of the program. Its prototype is as follows.
- void Py_Finalize()
The Py_Finalize function is used to close the Python interpreter and release the resources occupied by the interpreter. In addition to using the PyRun_SimpleString function, you can also use the PyRun_SimpleFile () function to run the ". py" script file. The function prototype is as follows.
- int PyRun_SimpleFile
( FILE *fp, const char *filename)
The parameter meanings are as follows. · Fp: Open File pointer. · Filename: name of the Python script file to be run. When using this function in Windows, pay attention to the version of the compiler used. Python officially released is compiled by Visual Studio 2003. NET. If a compiler of another version is used, FILE definitions are different due to version differences. Using a compiler of another version causes program crashes.
For convenience, you can use the following method to replace the PyRun_SimpleFile function to implement the same function.
- PyRun_SimpleString("execfile('file.py')");
Execfile is used to run the Python script file.