C ++ basic application guide for calling python script Functions

Source: Internet
Author: User

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:

 
  1. Py_Initialize (); // initialize python interpreter
  2. PyObject * pName = PyString_FromString ("test1"); // python script file name
  3. PyObject * pModule = PyImport_Import (pName); // import script, return pModule
  4. // PModule points to this script object
  5. If (! PModule)
  6. {
  7. Cout <"Can't find the file! "<Endl;
  8. Return 0;
  9. }
  10. Cout <"Get the function in. py" <endl;
  11. PyObject * pDict = PyModule_GetDict (pModule); // obtain the dictionary using the pModule
  12. // Pointer pDict
  13. PyObject * pFunc = PyDict_GetItemString (pDict, "Add ");
    // Get what you need through pDict
  14. // Function, where "Add" is test1.py
  15. // A funciton object
  16. PyObject * pParam = PyTuple_New (1); // enter the parameters required by the function.
  17. PyObject * pCurParam = PyInt_FromLong (10 );
  18. PyTuple_SET_ITEM (pParam, 0, pCurParam );
  19. PyObject * pAdded = PyObject_CallObject (pFunc, pParam );
    // Call this function and obtain
  20. // 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. Py_XDECREF (pAdded); // subtract one from the reference count
  24. Py_XDECREF (pCurParam );
  25. Py_XDECREF (pParam );
  26. // Py_XDECREF (pFunc );
  27. // Py_XDECREF (pDict );
  28. Py_XDECREF (pModule );
  29. Py_XDECREF (pName );
  30. Py_Finalize (); // close
  31. Python interpreter

This section describes how C ++ calls python script functions.

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.