Call the Python script function in C ++ Code The framework is as follows: 1 Py_initialize (); // initialize Python Interpreter
2
3 Pyobject * Pname = Pystring_fromstring ( " Test1 " ); // Python script file name
5 Pyobject * Pmodule = Pyimport_import (pname); // import script, return pmodule
// Pmodule points to this script object
7 If ( ! Pmodule)
8 {
9Cout<"Can't find the file!"<Endl;
10Return 0;
11}
12
14 Cout < " Get the function in. py " < Endl;
15 Pyobject * Pdict = Pymodule_getdict (pmodule); // obtain the dictionary using pmodule
// Pointer pdict
16 Pyobject * Pfunc = Pydict_getitemstring (pdict, " Add " ); // Use pdict to obtain
// Function, where "add" is test1.py
// A funciton object
17 Pyobject * Pparam = Pytuple_new ( 1 ); // Enter the parameters required by the function.
18 Pyobject * Pcurparam = Pyint_fromlong ( 10 );
19 Pytuple_set_item (pparam, 0 , Pcurparam );
20 Pyobject * Padded = Pyobject_callobject (pfunc, pparam); // call this function and obtain
// Return Value
21 Int Max = Pyint_aslong (padded); // converts the returned value to the Data Type of C ++
22 Cout < " After added, the number is " < Max < Endl;
23
24 Py_xdecref (padded); // subtract one from the reference count
25 Py_xdecref (pcurparam );
26 Py_xdecref (pparam );
27 // Py_xdecref (pfunc );
28 // Py_xdecref (pdict );
29 Py_xdecref (pmodule );
30 Py_xdecref (pname );
31
32 Py_finalize (); // close Python Interpreter
there are several issues that have not been solved yet:
1). I am using python25_d.dll and cannot find the function object in the *. py file edited by activepython. My activepython version is 2.4.
2 ). at the end of Program , the reference count of function object and dictionary object cannot be reduced by one. If you perform this operation, the program will crash.