Call the Python script function in the C ++ Program

Source: Internet
Author: User
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.

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.