Python provides a C + + library that makes it easy for developers to invoke Python modules from C + + programs. Next through this article to introduce the C + + call Python module knowledge, need to refer to the friendGenerally developed games know that Lua and C + + can be a good combination of each other, the Lua script as a similar dynamic link library to use, good use of the flexibility of script development. And as a popular general-purpose scripting language, Python is also possible. In a C + + application, we can use a set of plug-ins to implement some of the functions of the unified interface, the general plug-ins are implemented using the dynamic link library, if the plug-in changes more frequently, we can use Python instead of the dynamic link library form of plug-ins (as a text-style dynamic link library), This makes it easy to rewrite the script code as the requirements change, rather than having to recompile the link binary's dynamic-link library. The flexibility has been greatly improved.
As a glue language, Python can easily invoke C, C + + and other languages, and can also invoke Python's modules in other languages.
Python provides a C + + library that makes it easy for developers to invoke Python modules from C + + programs.
Specific documentation Reference Official guide:
Embedding Python in another application
Calling methods
1 link to Python call library
The Python installation directory already contains header files (include directories) and library files (Python27.lib under Windows).
You need to link to this library before you use it.
2 Calling Python statements directly
#include "python/Python.h"int main(){Py_Initialize(); ## 初始化PyRun_SimpleString("print 'hello'");Py_Finalize(); ## 释放资源}
3 Loading the Python module and calling the function
The ~/test directory contains test.py:
def test_add(a, b):print 'add ', a, ' and ', breturn a+b
You can call the Test_add function with the following code:
#include "Python/python.h" #include
Using namespace Std;int Main () {py_initialize ();//Initialize//To switch the Python work path to the directory where the module is to be called, make sure that the path name is correct string path = "~/test"; String chdir_cmd = String ("Sys.path.append (\") + path + "\") "; const char* cstr_cmd = Chdir_cmd.c_str (); pyrun_simplestring ("Import sys"); Pyrun_simplestring (cstr_cmd);//load module pyobject* modulename = pystring_fromstring ("test"); Module name, not file name pyobject* Pmodule = Pyimport_import (ModuleName), if (!pmodule)//Load module failed {cout << [ERROR] Python get Modu Le failed. "<< Endl;return 0;} cout << "[INFO] Python get module succeed." << endl;//load function pyobject* PV = pyobject_getattrstring (Pmodule, "tes T_add "); if (!PV | |! Pycallable_check (PV))//Verify Load Success {cout << "[ERROR] Can ' t ' find Funftion (test_add)" << Endl;return 0;} cout << "[INFO] Get function (Test_add) succeed." << endl;//Set parameters pyobject* args = pytuple_new (2); 2 parameters pyobject* arg1 = Pyint_fromlong (4); Parameter one is set to 4pyobject* arg2 = Pyint_fromlong (3); Parameter two is set to 3pytuple_setitem (args, 0, arg1); Pytuple_SetItem (args, 1, arg2);//Call function pyobject* PRet = Pyobject_callobject (PV, args);//Gets the parameter if (PRET)//verifies whether the call succeeded {long result = Py Int_aslong (PRet); cout << "Result:" << result;} Py_finalize (); # # Release resource return 0;}
Parameter passing
1 C + + passes parameters to Python
The parameters of Python are actually tuples, so the arguments actually construct an appropriate tuple.
There are two ways to use it:
Creating tuples with Pytuple_new, pytuple_setitem setting tuple values
PyObject* args = PyTuple_New(3);PyObject* arg1 = Py_BuildValue("i", 100); // 整数参数PyObject* arg2 = Py_BuildValue("f", 3.14); // 浮点数参数PyObject* arg3 = Py_BuildValue("s", "hello"); // 字符串参数PyTuple_SetItem(args, 0, arg1);PyTuple_SetItem(args, 1, arg2);PyTuple_SetItem(args, 2, arg3);
Using Py_buildvalue to construct tuples directly
PyObject* args = Py_BuildValue("ifs", 100, 3.14, "hello");PyObject* args = Py_BuildValue("()"); // 无参函数
Format strings such as I, S, and F can refer to format strings
2 Convert Python return value
All the calls to Python get are pyobject objects, so you need to use some of the functions in the library provided by Python to convert the return value to C + +, such as pyint_aslong,pyfloat_asdouble, pystring_asstring, and so on.
You can also use the Pyarg_parsetuple function to parse the return value as a tuple.
Pyarg_parse is also an easy-to-use conversion function.
Pyarg_parsetuple and Pyarg_parse both use format strings
Precautions
The need to switch Python's working directory to the module's path is loaded by module name instead of file name module load or the function load needs to be validated for success, otherwise it may cause a stack error to cause the program to crash by using Py_decref (pyobject*) to dismiss the object's reference ( For Python garbage Collection)