A brief analysis of C + + calling Python module

Source: Internet
Author: User

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();      ## 释放资源}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
3 Loading PythonModule and call function

~/testThe catalogue contains test.py :

def test_add(a, b):    print ‘add ‘, a, ‘ and ‘, b return a+b
    • 1
    • 2
    • 3
    • 1
    • 2
    • 3

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_Newto 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);
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
  • Using Py_buildvalue to construct tuples directly

    PyObject* args = Py_BuildValue("(ifs)", 100, 3.14, "hello");PyObject* args = Py_BuildValue("()"); // 无参函数
    • 1
    • 2
    • 1
    • 2

    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_ParseIt is also a convenient conversion function.

PyArg_ParseTupleand PyArg_Parse both use the format string

Precautions
    1. Need to switch Python 's working directory to the path where the module resides
    2. Load by module name instead of file name
    3. Module loading or function loading requires validation to be successful, or it may cause a stack error to cause the program to crash
    4. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.