A deep analysis of C + + calling Python module _c language

Source: Internet
Author: User
Tags garbage collection lua

The game has been developed in general know that Lua and C + + can be a good combination of each other, the Lua script as a similar dynamic link library to use, good use of scripting development flexibility. And as a popular general-purpose scripting language Python, it can be done. In a C + + application, we can use a set of plug-ins to implement a number of functions with a unified interface, the general Plug-ins are implemented using dynamic link library, if the plug-in changes more frequently, we can use Python to replace the dynamic link library in the form of plug-ins (can be a text-form dynamic link library), This makes it easy to rewrite script code based on changes in requirements, rather than having to recompile the link binary dynamic link library. The flexibility is greatly improved.

As a glue language, Python can easily invoke languages such as C, C + +, and can invoke Python's modules in other languages.

Python provides a C + + library that makes it easy for developers to invoke Python modules from C + + programs.

Refer to the official Guide for specific documentation:

Embedding Python in Another application

Call method

1 link to Python call library

The Python installation directory already contains header files (include directories) and library files (Python27.lib under Windows).

You need to link to this library before you use it.

2 Calling Python statements directly

<code class= "Language-cpp hljs" > #include "python/python.h"
int main ()
{
py_initialize (); # # Initialize
pyrun_simplestring ("print ' Hello '");
Py_finalize (); # # Release Resources
}
</code>

3 Loading the Python module and calling the function

The ~/test directory contains test.py:

<code class= "Language-python hljs" >def Test_add (A, b):
print ' Add ', A, ' and ', B return
a+b</code>

You can call the Test_add function by using the following code:

<code class= "Language-cpp hljs" > #include "python/python.h" #include <iostream> using namespace std; int main () {py_initialize ()////To switch the Python work path to the directory where the module is to be invoked, make sure the path name is correct string path = "~/test"; string chdir_cmd = St
Ring ("Sys.path.append (\") + path + "\");
Const char* Cstr_cmd = Chdir_cmd.c_str ();
pyrun_simplestring ("Import sys");
Pyrun_simplestring (Cstr_cmd); Load module pyobject* modulename = pystring_fromstring ("test");
Module name, not filename pyobject* pmodule = pyimport_import (modulename); if (!pmodule)//Load module failed {cout << [ERROR] Python get module failed. "<< Endl; return 0;} cout <<" [INF
O] Python get module succeed. "<< Endl;
Load function pyobject* PV = pyobject_getattrstring (Pmodule, "Test_add"); if (!PV | |!)  Pycallable_check (PV))//Verify that the load is successful {cout << "[ERROR] Can ' t find Funftion (test_add)" << Endl; return 0;} cout
<< [INFO] Get function (Test_add) succeed. "<< Endl; Set parameter pyobject* args = Pytuple_new (2); 2 Parameters Pyobject* Arg1 = Pyint_fromlong (4); The parameter is set to 4 pyobject* arg2 = Pyint_fromlong (3);
Parameter two is set to 3 Pytuple_setitem (args, 0, arg1);
Pytuple_setitem (args, 1, arg2);
Call function pyobject* PRet = Pyobject_callobject (PV, args);
Gets the parameter if (PRET)//verifies that the call succeeded {long result = Pyint_aslong (PRet); cout << "Results:" << result} Py_finalize ();
# # Release resources return 0; } </iostream></code>

Parameter passing

1 C + + Pass parameters to Python

The parameters of Python are actually tuples, so the argument is actually constructing an appropriate tuple.

There are two common ways to do this:

Create tuples using pytuple_new, Pytuple_setitem set tuple values

<code class= "Language-cpp hljs" >pyobject* args = pytuple_new (3);
pyobject* arg1 = Py_buildvalue ("i", 100); Integer parameter
pyobject* arg2 = Py_buildvalue ("f", 3.14);//floating-point number parameter
pyobject* arg3 = Py_buildvalue ("s", "Hello");//String parameters
Pytuple_setitem (args, 0, arg1);
Pytuple_setitem (args, 1, arg2);
Pytuple_setitem (args, 2, arg3);</code>

Directly using the Py_buildvalue constructor tuple

<code class= "Language-cpp hljs" >pyobject* args = Py_buildvalue ("ifs", MB, 3.14, "Hello");
pyobject* args = Py_buildvalue ("()"); No-parameter function </code>

Format strings of I, S, F can refer to the format string

2 Convert Python return value

Calling Python gets all the Pyobject objects, so you need to use some of the functions in the library provided by Python to convert the return value to C + +, such as pyint_aslong,pyfloat_asdouble, pystring_asstring, and so on.

You can also use the Pyarg_parsetuple function to parse the return value as a tuple.

Pyarg_parse is also an easy to use conversion function.

Pyarg_parsetuple and Pyarg_parse both use format strings

Attention matters

You need to switch the Python working directory to the path where the module is loaded instead of the filename module loading or the function load needs to verify the success or failure, or it may cause a stack error causing the program to crash using Py_decref (pyobject*) to dismiss the object's reference ( For Python garbage Collection)

The above is a small set to introduce the C + + call Python modules related knowledge, I hope to help!

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.