A brief analysis of C + + calling Python module
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 Method 1 links to
PythonCall Library
The Python installation directory already contains header files ( include
directories) and library files (under Windows python27.lib
).
You need to link to this library before you use it.
2 Direct call
PythonStatement
#include "python/Python.h"int main(){ Py_Initialize(); ## 初始化 PyRun_SimpleString("print ‘hello‘"); Py_Finalize(); ## 释放资源}
3 Loading
PythonModule and call function
~/test
The catalogue contains test.py
:
def test_add(a, b): print ‘add ‘, a, ‘ and ‘, b return a+b
You can call the function with the following code test_add
:
#include "Python/python.h"#include <iostream>UsingNamespaceStdint main () {py_initialize ();InitializationTo switch the python work path to the directory where the module is to be called, make sure that the path name is correctString path ="~/test";String chdir_cmd =String"Sys.path.append (\" ") + path +"\")";Constchar* 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)Failed to load module {cout <<"[ERROR] Python get module failed." << Endl;Return0; }cout <<"[INFO] Python get module succeed." << Endl;Load function pyobject* PV = pyobject_getattrstring (Pmodule,"Test_add");if (!PV | |!) Pycallable_check (PV))Verify that the load is successful {cout <<"[ERROR] Can ' t find Funftion (test_add)" << Endl;Return0; }cout <<"[INFO] Get function (Test_add) succeed." << Endl;Set parameter pyobject* args = Pytuple_new (2); //2 parameters pyobject* arg1 = Pyint_fromlong (4); //parameter is set to 4 pyobject* arg2 = Pyint_fromlong (3); //parameter two is set to 3 Pytuple_setitem (args, 0, arg1); Pytuple_setitem (args, 1, arg2); //call function pyobject* PRet = Pyobject_callobject (PV, args); //Get parameters if (pRet) //verify whether the call succeeded { Span class= "Hljs-keyword" >long result = Pyint_aslong (PRet); cout << "result:" << result;} Py_finalize (); ## release resources return 0;}
1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- Ten
- one
-
- 2
- (
- )
- +
- +
- /
- 0
-
- +
-
- all
- +
- +
- +
- -
- 29
-
- +
- +
- all
-
- +
- +
- PNS
- up
i>39
-
- 48
- all
-
-
- /
- /
- /
- /li>
-
-
- ,
- ,
- ,
- up-
- -
- +
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21st
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
Parameter passing 1
C + +To
PythonPassing parameters
The parameters of Python are actually tuples, so the arguments actually construct an appropriate tuple.
There are two ways to use it:
PyTuple_New
to set a tuple value using create tuple PyTuple_SetItem
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("()"); // 无参函数
i
, s
f
such as format strings can refer to format strings
2 Conversion
Pythonreturn 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 + + , for example, and PyInt_AsLong
PyFloat_AsDouble
PyString_AsString
so on.
You can also use PyArg_ParseTuple
a function to parse the return value as a tuple.
PyArg_Parse
It is also a convenient conversion function.
PyArg_ParseTuple
and PyArg_Parse
both use the format string
Precautions
- Need to switch Python 's working directory to the path where the module resides
- Load by module name instead of file name
- Module loading or function loading requires validation to be successful, or it may cause a stack error to cause the program to crash
- Need
Py_DECREF(PyObject*)
to use to dismiss an object's reference (for Python garbage collection)
http://blog.csdn.net/tobacco5648/article/details/50890106
A brief analysis of C + + calling Python module