Python calls the C function

Source: Internet
Author: User

Python calls C

A typical Python extension should contain at least three parts: Export functions, method lists, and initialization functions. Example:

123456789101112131415161718192021222324252627282930 example.cintfact(intn){        if(n <= 1)        return1;        else        returnn * fact(n - 1);}wrap.c#include <Python.h>PyObject* wrap_fact(PyObject* self, PyObject* args){        intn, result;                if(! PyArg_ParseTuple(args, "i:fact", &n))        return NULL;        result = fact(n);        returnPy_BuildValue("i", result);}staticPyMethodDef exampleMethods[] ={        {"fact", wrap_fact, METH_VARARGS, "Caculate N!"},        {NULL, NULL}};voidinitexample(){        PyObject* m;        m = Py_InitModule("example", exampleMethods);}

1. Export function to use a function in the C language in the Python interpreter, first write the appropriate export function for it, the export function in the above example is wrap_fact. In Python's C language extension, all the exported functions have the same function prototypes:

1 PyObject* method(PyObject* self, PyObject* args);

The function is an interface between the Python interpreter and the C function, with two parameters: Self and args. The parameter self is only used when the C function is implemented as an inline method (built-in), usually with a value of NULL (NULL). The parameter args contains all the parameters that the Python interpreter will pass to the C function, usually using the function pyarg_parsetuple () provided by the Python C extension interface to obtain these parameter values. All the exported functions return a pyobject pointer, and if the corresponding C function does not have a true return value (that is, the return value type is void), then a global None object (Py_none) should be returned, and its reference count will be increased by 1, as follows:

12345 PyObject* method(PyObject *self, PyObject *args){        Py_INCREF(Py_None);        returnPy_None;}

2. The method list method list shows all the methods that can be used by the Python interpreter, and the corresponding method list for the above example is:

12345 static   pymethoddef examplemethods[] = { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; Code class= "Java plain" >{ "fact" , Wrap_fact, meth_ varargs,  "Caculate n!"          {null, NULL} };

Each item in the method list consists of four parts: The method name, the export function, the parameter passing method, and the method description. The method name is the name used when calling the method from the Python interpreter. The parameter passing method specifies the specific form of the python to pass the parameter to the C function, the optional two ways are Meth_varargs and meth_keywords, in which Meth_varargs is the standard form of the parameter passing, It passes the parameters between the Python interpreter and the C function through a python tuple, and if Meth_keyword is used, the Python interpreter and the C function will pass the argument between the two through the Python dictionary type.

3. Initialization function All Python extensions must have an initialization function so that the Python interpreter can initialize the module correctly. The Python interpreter specifies that all function names for the initialization function must begin with INIT and add the module's name. For module example, the corresponding initialization function is:

12345 voidinitexample(){        PyObject* m;        m = Py_InitModule("example", exampleMethods);}

When the Python interpreter needs to import the module, it will find the appropriate initialization function based on the name of the module and, once found, call the function to do the appropriate initialization, and initialize the function by calling the function Py_initmodule () provided by Python's C extension interface. To register all the available methods in the module with the Python interpreter.

4. Compiled under Linux, compiled into so library, Python can import directly. Under Windows, you need to modify the suffix of the DLL to Pyd,python to be recognized.

12345 gcc -fpic -c -I/usr/include/python2.5\-I /usr/lib/python2.5/config \example.c wrapper.cgcc -shared -o example.so example.o wrapper.o

5. Python calls

1234 >>> importexample>>> example.fact(4)24>>>

Python calls the C function

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.