Python and C call each other

Source: Internet
Author: User

While Python development is highly efficient, it is not very performance as a scripting language, so in order to take into account development efficiency and performance, it is common to implement high performance modules in C or C + + or run Python scripts in C or C + + to handle logic, which is usually the way some of the modules in Python are implemented. The latter is more common in server-side programs (for business expansion or plugin functionality) and game development (scripts only handle logic). This article focuses on the implementation of Python and C by running Python scripts in C, and the use of the same area of memory by C and Python scripts as an example.

Preparatory work

In order to run a Python script in C, you need to link the Python virtual Library to the program link, the Python virtual library is the Python27.lib file in the Python installation directory libs, and the library link into the program can be Google. Because some python methods and data structures are used in C, the include directory under the Python installation directory needs to be added to the project include directory. Well, that's all you need to prepare, and then you can start implementing an example of setting up a memory area.

Embedded Python virtual machine

Embedding a Python virtual machine in C is simple, just include the Python.h header file at the beginning of the program, and then invoke the following two paragraphs to initialize the Python virtual machine instance.

1 py_setpythonhome ("D:\Python27"); 2 py_initialize ();

The Py_setpythonhome function is used to set up Python's library path, which is the Python installation path, and the Py_initialize function actually instantiates a Python virtual machine, which embeds a Python virtual machine into C.

Invoking a Python script

After you initialize the Python virtual machine, you can actually invoke the Python script. The methods in the call script module in C are divided into the following steps:

1, using pyimport_importmodule to import footstep module;

2, use pyobject_getattrstring to obtain the module specific method information;

3, using py_vabuildvalue conversion input parameters;

4, using Pyobject_callobject to invoke the specific method;

5, using the Pyarg_parse conversion method return results.

Because the above process is necessary to invoke the method in the module, you can write a function to encapsulate the above 5 steps, the code is as follows:

1 intPymodulerunfunction (Const Char*module,Const Char*function,2                         Const Char*result_format,void*result,Const Char*Args_format, ...)3 {4 5Pyobject *pmodule, *pfunction, *args, *presult;6 7Pmodule = Pyimport_importmodule (const_cast<Char*>(module));8     if(!pmodule)9     {TenPyobject *type =pyerr_occurred (); One         if(Type = =pyexc_nameerror) A         { - pyerr_clear (); -             return 0; the         } -  -Pyerror ("pymodulerunfunction"); -         return-1; +     } -  +Pfunction = pyobject_getattrstring (Pmodule, const_cast<Char*>(function)); A Py_decref (pmodule); at     if(!pfunction) -     { -Pyobject *type =pyerr_occurred (); -         if(Type = =pyexc_attributeerror) -         { - pyerr_clear (); in             return 0; -         } to  +Pyerror ("pymodulerunfunction"); -         return-2; the     } *  $     if(Pfunction = =Py_none)Panax Notoginseng     { -         return 0; the     } +  A va_list args_list; the Va_start (args_list, Args_format); +args = Py_vabuildvalue (const_cast<Char*>(Args_format), args_list); - va_end (args_list); $  $     if(!args) -     { - Py_decref (pfunction); the         return-3; -     }Wuyi  thePresult =pyobject_callobject (pfunction, args); -     if(Presult = =0) Wu     { -Pyerror ("pymodulerunfunction"); About Py_xdecref (pfunction); $ py_xdecref (args); -         return-1; -     } -  A Py_xdecref (pfunction); + py_xdecref (args); the  -     returnConvertResult (presult, Result_format, result); $}
View Code

With the general function of invoking the methods in the Python module above, we can invoke the methods in the Python script directly, as follows:

1 pymodulerunfunction ("Hello", "Test", "" ", 0," () ");

This allows us to implement the method of calling Python in C again. Let's go back to the happy Python how to invoke the method in C.

Initializing the C implementation of the Python module

In order to be able to invoke the method defined in C in a Python script, you need to define a Python module in C, then import the module in the script, and then indirectly invoke the method defined in C with this module. For example, we define a chunk of memory by C and the function SetData and GetData (code below) to manipulate this memory area, how do I invoke the SetData and GetData functions in the script to manipulate data? The key question is how to invoke the SetData and GetData functions in a script, and if you can invoke them in a script, you will be able to manipulate data. Python solves this problem in a modular way.

1 #defineMin (b) ((a) < (a))? (a): (b))2 3 Chardata[1024x768];4 5 voidSetData (Const Char*str)6 {7strncpy (data, str, MIN (strlen (str) +1,1024x768));8 }9 Ten Const Char*GetData () One { A     returndata; -}

There are specific steps for defining a Python module in C, with the following specific code:

1Pydoc_strvar (pysetdata_doc__,"\2 Test \ n3 \ n4 pysetdata (str) \ n5 str: In and out of the string \ n6 return: \ n7 NULL\ n8 ");9 Staticpyobject* Pysetdata (Pyobject *self, Pyobject *args)Ten { One     Const Char* str =NULL; A     if( ! Pyarg_parsetuple (args,"s", &str)) -     { -         return 0; the     } - SetData (str); - Py_return_none; - } +  -Pydoc_strvar (pygetdata_doc__,"\ + print data \ n A \ n at pygetdata () \ n - return: \ n - data \ n - "); - Staticpyobject* Pygetdata (Pyobject *self, Pyobject *args) - { in     Const Char* str =NULL; -     returnpystring_fromstring (GetData ()); to } +  - StaticPymethoddef module_methods[] = { the{"Py_set_data", Pysetdata, Meth_varargs, pysetdata_doc__}, *{"Py_get_data", Pygetdata, Meth_varargs, pygetdata_doc__}, $ {NULL}Panax Notoginseng     }; - voidinitccallpy () the { +Pyobject *module = Py_initmodule3 ("PYCALLC", Module_methods, A         "python call C"); the}
View Code

Py_initmodule3 is used to define a Python module, the first parameter is the name of the module, the second parameter is a collection of method descriptions in the module, and the third parameter is the description of the module. In the above code we define a module called PYCALLC, the method description set Module_methods describes two methods Py_set_data and Py_get_data, the corresponding function addresses of the two methods are Pysetdata and Pygetdata, The two functions will eventually invoke the previously defined SetData and GetData respectively. This allows us to set up and retrieve data from the Python script using the Py_set_data and Py_get_data methods of the PYCALLC module. See the above implementation, in fact, the main function of this Python module is to encapsulate the functions defined in C once again, the encapsulated function can be recognized by Python.

Invoking the C implementation of the Python module in a python script

Since a Python module PYCALLC has already been initialized with C code, in the script we can import the module via import and invoke the function in this module. The specific code is as follows:

1 # -*-coding:utf-8-*- 2 3 Import PYCALLC 4 5 def Test (): 6     Print '  ', Pycallc.py_get_data ()7     pycallc.py_set_data (" Change Hello world! ")

This allows us to implement the method in the Python script called C.

The above complete code demo link: https://github.com/morningstatus/python/tree/master/ccallpy

Summarize

From the above C call Python,python call C, in fact, are some fixed steps, know it will be used, there is no problem, only want to know the problem. You may think it's very advanced without touching it, but it's not so hard to get a little bit of thought into it. A lot of computer technology is just like this, only you want to not the problem, not you will not question, ask more, think more, learn more, one day you can also become a technology Daniel.

Reference

Python official: https://docs.python.org/2/c-api/index.html

Python and C call each other

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.