C ++ calls the basic functions of Python and calls the basic functions of python.

Source: Internet
Author: User

C ++ calls the basic functions of Python and calls the basic functions of python.

C ++ calls Python to install Python first. Taking win7 as an example, the Python path is c: \ Python35 \, and c ++ code is compiled through mingw.
To compile a makefile file, you must first add the inclusion path:
Inc_path + = c:/Python35/include
Then add the link parameters:
Ld_flag + = c:/Python35/libs/libpython35.a
Add header file reference to the source file:
# Include "Python. h"
The Python interpreter must be initialized and terminated after the task is completed:

1 void start () 2 {3 int r = Py_IsInitialized (); // 1 indicates that 4 if (r = 0) has been initialized) 5 {6 // Py_SetPythonHome (L "C :\\ Python35"); 7 Py_Initialize (); // initialize 8 p_main_Module = PyImport_ImportModule ("_ main __"); 9 if (! P_main_Module) 10 {11 throw ""; 12} 13} 14} 15 void end () 16 {17 Py_Finalize (); // clear 18}

During program deployment, you can copy the c: \ Python35 \ lib directory to the execution path, or set the Python installation directory through Py_SetPythonHome (L "C: \ Python35.
Basic Requirements for C ++ to call Python:
1. Run Python commands

PyRun_SimpleString("print(os.getcwd(),a)");pyext.eval(R"(a+='qwer')");

2. Load the Python Module

PyObject * pModule = PyImport_ImportModule ("tp"); // test: Python file name. If the script has an error, null PyRun_SimpleString ("import OS") is returned ");

3. assign values to Python Variables

For numeric values, use Py_BuildValue:

Py_BuildValue("") NonePy_BuildValue("i", 123) 123Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)Py_BuildValue("s", "hello") 'hello'Py_BuildValue("ss", "hello", "world") ('hello', 'world')Py_BuildValue("s#", "hello", 4) 'hell'Py_BuildValue("()") ()Py_BuildValue("(i)", 123) (123,)    Py_BuildValue("(ii)", 123, 456) (123, 456)Py_BuildValue("(i,i)", 123, 456) (123, 456)Py_BuildValue("[i,i]", 123, 456) [123, 456]Py_BuildValue("{s:i,s:i}", "abc", 123, "def", 456) {'abc': 123, 'def': 456}

For other data structures, use the corresponding function settings, for example:

PyObject * pArgs = PyTuple_New (1); PyObject * pDict = PyDict_New (); // create the dictionary type variable PyDict_SetItemString (pDict, "Name", Py_BuildValue ("s ", "WangYao"); // fill in the Data PyDict_SetItemString (pDict, "Age", Py_BuildValue ("I", 25) to the dictionary type variable )); // fill in the Data PyTuple_SetItem (pArgs, 0, pDict) to the dictionary type variable; // 0 --- the serial number adds the dictionary type variable to the parameter tuples

After the object is constructed, set it to Python through PyObject_SetAttrString:

PyObject * ps = PyUnicode_DecodeUTF8 (val, strlen (val), "ignore"); // constructs an object PyObject_SetAttrString (p_main_Module, key, ps); // set

4. Obtain the value of the Python variable.
First, get the pointer of the variable, and then parse it through PyArg_Parse.

PModule = PyImport_ImportModule ("_ main _"); pReturn = PyObject_GetAttrString (pModule, "a"); // you can obtain the global variable int size = PyDict_Size (pReturn ); pyObject * pNewAge = PyDict_GetItemString (pReturn, "Age"); int newAge; PyArg_Parse (pNewAge, "I", & newAge );

Analysis of tuples:

int ok;ok = PyArg_ParseTuple(args, "s", &s); //Python call: f('whoops!')ok = PyArg_ParseTuple(args, "lls", &k, &l, &s);//Python call: f(1, 2,'three')ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);//Python call: f((1, 2), 'three')ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);//Python calls://f('spam')//f('spam', 'w')//f('spam', 'wb', 100000)

5. Call Python Functions

PyObject * pfun = PyObject_GetAttrString (pModule, "testdict"); // testdict: function name in the Python file: PyObject * pReturn = PyEval_CallObject (pfun, pArgs); // call the Function

6. Set the function for Python to call
Define the c function, declare the method list, declare the module, add the module, and call

Static int numargs = 1890; static PyObject * emb_numargs (PyObject * self, PyObject * args) // C function {if (! Callback (args, ": numargs") return NULL; return PyLong_FromLong (numargs);} static PyMethodDef EmbMethods [] = {// method list {"numargs", emb_numargs, METH_VARARGS, "Return the number of arguments already ed by the process. "},{ NULL, NULL, 0, NULL }}; static PyModuleDef EmbModule ={// the module declares PyModuleDef_HEAD_INIT," emb ", NULL,-1, EmbMethods, NULL, NULL, NULL, NULL}; static PyObject * PyInit_emb (void) // module initialization function {return PyModule_Create (& EmbModule);} // Add module: PyImport_AppendInittab ("emb ", & PyInit_emb); // Add the Python code of a module: import embprint ("Number of arguments", emb. numargs ())

 

Related Article

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.