Analysis on C ++ calling Python Module

Source: Internet
Author: User

Analysis on C ++ calling Python Module
Analysis on C ++ calling Python Module

As a glue language,PythonEasy to callC,C ++Can also be called in other languages.PythonModule.

PythonProvidedC ++Library, so that developers can easilyC ++Program callPythonModule.

For specific documents, refer to the official guide:
Embedding Python in Another Application

Call method 1 Link PythonCall Library

PythonThe installation directory contains the header file (includeDirectory) and library files (WindowsWhich ispython27.lib).

You need to link to this library before using it.

2. Direct call PythonStatement
# Include "python/Python. h" int main () {Py_Initialize (); # initialize PyRun_SimpleString ("print 'hello'"); Py_Finalize (); # release resources}
3 load PythonModule and call Functions

~/testDirectory containstest.py:

def test_add(a, b):    print 'add ', a, ' and ', b    return a+b

You can use the following code to calltest_addFunction:

# Include "python/Python. h" # include
  
   
Using namespace std; int main () {Py_Initialize (); // initialize // switch the Python working path to the directory where the module to be called is located. Ensure that the path name is correct. string path = "~ /Test "; string chdir_cmd = string (" sys. path. append (\ "") + path + "\") "; const char * cstr_cmd = chdir_1_.c_str (); PyRun_SimpleString (" import sys "); PyRun_SimpleString (cstr_cmd ); // load the module PyObject * moduleName = PyString_FromString ("test"); // The Module name, not the file name PyObject * pModule = PyImport_Import (moduleName); if (! PModule) // failed to load the module {cout <"[ERROR] Python get module failed. "<endl; return 0 ;}cout <" [INFO] Python get module succeed. "<endl; // load function PyObject * pv = PyObject_GetAttrString (pModule," test_add "); if (! Pv |! PyCallable_Check (pv) // verify whether the load is successful {cout <"[ERROR] Can't find funftion (test_add)" <endl; return 0 ;} cout <"[INFO] Get function (test_add) succeed. "<endl; // set the PyObject * args = PyTuple_New (2); // two parameters: PyObject * arg1 = PyInt_FromLong (4 ); // set parameter 1 to 4 PyObject * arg2 = PyInt_FromLong (3); // set parameter 2 to 3 PyTuple_SetItem (args, 0, arg1); PyTuple_SetItem (args, 1, arg2); // call the function PyObject * pRet = PyObject_CallObject (pv, args); // obtain the parameter if (pRet) // verify whether the call is successful {long result = PyInt_AsLong (pRet); cout <"result:" <result;} Py_Finalize () ;## release resource return 0 ;}
  
Parameter transfer 1 C ++Direction PythonPASS Parameters

PythonThe parameter is actually a tuple, so passing the parameter is actually constructing a suitable tuple.

There are two common methods:

UsePyTuple_NewCreate tuples,PyTuple_SetItemSet the tuples

PyObject * args = PyTuple_New (3); PyObject * arg1 = Py_BuildValue ("I", 100); // The integer parameter PyObject * arg2 = Py_BuildValue ("f", 3.14 ); // Floating Point Number Parameter PyObject * arg3 = Py_BuildValue ("s", "hello"); // string parameter PyTuple_SetItem (args, 0, arg1); PyTuple_SetItem (args, 1, arg2); PyTuple_SetItem (args, 2, arg3 );

Directly use Py_BuildValue to construct the tuples

PyObject * args = Py_BuildValue ("ifs", 100, 3.14, "hello"); PyObject * args = Py_BuildValue ("()"); // No Parameter Function

i,s,fFor more information about format strings, see format strings.

2 Conversion PythonReturn Value

CallPythonAll obtained are PyObject objects, so you need to usePythonSome functions in the provided library convert the return valueC ++For examplePyInt_AsLong,PyFloat_AsDouble,PyString_AsString.

You can also usePyArg_ParseTupleFunction to parse the returned values as tuples.

PyArg_ParseIt is also a convenient conversion function.

PyArg_ParseTupleAndPyArg_ParseBoth use format strings

Note: PythonTo switch to the module path, load the module by the module name instead of the file name module, or verify whether the function is loaded successfully. Otherwise, a stack error may occur, causing program crash. Py_DECREF(PyObject*)To remove object references (for Python garbage collection)

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.