The C ++ programming language is widely supported and can be used in a variety of ways, for example, you can call some applications of C # and the methods for C ++ to call python script functions described today. Next let's take a look at how C ++ calls the python script function.
The code for C ++ to call a python script function is as follows:
- Py_Initialize (); // initialize python interpreter
- PyObject * pName = PyString_FromString ("test1"); // python script file name
- PyObject * pModule = PyImport_Import (pName); // import script, return pModule
- // PModule points to this script object
- If (! PModule)
- {
- Cout <"Can't find the file! "<Endl;
- Return 0;
- }
- Cout <"Get the function in. py" <endl;
- PyObject * pDict = PyModule_GetDict (pModule); // obtain the dictionary using the pModule
- // Pointer pDict
- PyObject * pFunc = PyDict_GetItemString (pDict, "Add ");
// Get what you need through pDict
- // Function, where "Add" is test1.py
- // A funciton object
- PyObject * pParam = PyTuple_New (1); // enter the parameters required by the function.
- PyObject * pCurParam = PyInt_FromLong (10 );
- PyTuple_SET_ITEM (pParam, 0, pCurParam );
- PyObject * pAdded = PyObject_CallObject (pFunc, pParam );
// Call this function and obtain
- // Return Value
- Int max = PyInt_AsLong (pAdded); // converts the returned value to the Data Type of c ++
- Cout <"after added, the number is" <max <endl;
- Py_XDECREF (pAdded); // subtract one from the reference count
- Py_XDECREF (pCurParam );
- Py_XDECREF (pParam );
- // Py_XDECREF (pFunc );
- // Py_XDECREF (pDict );
- Py_XDECREF (pModule );
- Py_XDECREF (pName );
- Py_Finalize (); // close
- Python interpreter
This section describes how C ++ calls python script functions.