Simple Getting Started Guide for Python program extension using C language, python

Source: Internet
Author: User

Simple Getting Started Guide for Python program extension using C language, python

I. Introduction

Python is a powerful high-level scripting language. It is powerful not only in its own functions, but also in its excellent scalability, python has been favored by more and more people and has been successfully applied to the development of various large software systems.

Different from other common scripting languages, Python programmers can use APIs provided by the Python language to use C or C ++ for Functional extension of Python, in this way, you can use Python's convenient and flexible syntax and functions, and obtain almost the same execution performance as C or C ++. Slow execution speed is a common feature of almost all scripting languages, and it is also an important factor that has been criticized. Python cleverly solves this problem through the organic combination with the C language, therefore, the application scope of the script language is greatly extended.

When developing a real Software System Using Python, C/C ++ is often used to expand Python. The most common situation is that a library written in C already exists. You need to use some functions of this library in the Python language. In this case, you can use the extension functions provided by Python. In addition, because Python is essentially a scripting language, it is difficult for some functions to be implemented using Python to meet the execution efficiency requirements of the actual software system, in this case, you can use the extension function provided by Python to implement these key code segments in C or C ++ to provide program execution performance.

This article mainly introduces the C language extension interfaces provided by Python, and how to use these interfaces and C/C ++ languages to perform Functional extension of Python, it also describes how to implement Python function expansion with specific examples.

Ii. Python C Language Interface

Python is a scripting language implemented in C language. It has excellent openness and scalability, and provides convenient and flexible application interface (API ), this allows C/C ++ programmers to expand the functions of the Python interpreter at various levels. Before using C/C ++ to Expand functions of Python, you must first understand the C language interface provided by the Python interpretation.
2.1 Python object)

Python is an object-oriented scripting language. All objects are expressed as PyObject In the Python interpreter. The PyObject structure contains all member pointers of the Python object, maintain the type information and reference count of Python objects. During Python extension programming, once Python objects must be processed in C or C ++, A PyObject structure should be maintained.

In Python C Language extension interfaces, most functions have one or more parameters of the PyObject pointer type, and most of the returned values are PyObject pointers.
2.2 reference count

To simplify memory management, Python implements the automatic garbage collection function through the reference counting mechanism. Each object in Python has a reference count, it is used to count the number of times the object is referenced in different places. Every time a Python object is referenced, the corresponding reference count increases by 1. Every time a Python object is destroyed, the corresponding reference is reduced by 1. Only when the reference count is zero, to delete Python objects from the memory.

The following example illustrates how the Python interpreter manages Pyhon objects by using reference counts:

Example 1: refcount. py

Class refcount: # etc. r1 = refcount () # reference count is 1r2 = r1 # reference count is 2del (r1) # reference count is 1del (r2) # reference count is 0, delete an object

When processing Python objects in C/C ++, correct maintenance of the reference count is a key issue. If it is not handled properly, memory leakage may occur. Python's C language interface provides some macros to maintain the reference count. The most common is to use Py_INCREF () to increase the reference count of Python objects by 1, and use Py_DECREF () to reduce the reference count of Python objects by 1.
2.3 Data Type

Python defines six data types: integer, floating point, String, tuples, lists, and dictionaries, first, you need to know how to convert data types in C and Python.

2.3.1 integer, floating point, and string

It is relatively simple to use integer, floating point, and string data types in Python C Language extension. You only need to know how to generate and maintain them. The following example shows how to use Python in C:

Example 2: typeifs. c

// build an integerPyObject* pInt = Py_BuildValue("i", 2003);assert(PyInt_Check(pInt));int i = PyInt_AsLong(pInt);Py_DECREF(pInt);// build a floatPyObject* pFloat = Py_BuildValue("f", 3.14f);assert(PyFloat_Check(pFloat));float f = PyFloat_AsDouble(pFloat);Py_DECREF(pFloat);// build a stringPyObject* pString = Py_BuildValue("s", "Python");assert(PyString_Check(pString);int nLen = PyString_Size(pString);char* s = PyString_AsString(pString);Py_DECREF(pString);
2.3.2 tuples

The tuples In the Python language are fixed-length arrays. When the Python interpreter calls methods in the C language extension, all non-keyword parameters are transmitted as tuples. The following example demonstrates how to use Python's tuples in C:

Example 3: typetuple. c

// create the tuplePyObject* pTuple = PyTuple_New(3);assert(PyTuple_Check(pTuple));assert(PyTuple_Size(pTuple) == 3);// set the itemPyTuple_SetItem(pTuple, 0, Py_BuildValue("i", 2003));PyTuple_SetItem(pTuple, 1, Py_BuildValue("f", 3.14f));PyTuple_SetItem(pTuple, 2, Py_BuildValue("s", "Python"));// parse tuple itemsint i;float f;char *s;if (!PyArg_ParseTuple(pTuple, "ifs", &i, &f, &s))  PyErr_SetString(PyExc_TypeError, "invalid parameter");// cleanupPy_DECREF(pTuple);
2.3.3 list

The list in Python is a variable-length array. The list is more flexible than the tuples. You can use the list to randomly access the Python objects stored in it. The following example demonstrates how to use the Python list type in the C language:

Example 4: typelist. c

// create the listPyObject* pList = PyList_New(3); // new referenceassert(PyList_Check(pList));// set some initial valuesfor(int i = 0; i < 3; ++i)  PyList_SetItem(pList, i, Py_BuildValue("i", i));// insert an itemPyList_Insert(pList, 2, Py_BuildValue("s", "inserted"));// append an itemPyList_Append(pList, Py_BuildValue("s", "appended"));// sort the listPyList_Sort(pList);// reverse the listPyList_Reverse(pList);// fetch and manipulate a list slicePyObject* pSlice = PyList_GetSlice(pList, 2, 4); // new referencefor(int j = 0; j < PyList_Size(pSlice); ++j) { PyObject *pValue = PyList_GetItem(pList, j); assert(pValue);}Py_DECREF(pSlice);// cleanupPy_DECREF(pList);
2.3.4 dictionary

The dictionary in Python is a data type accessed Based on keywords. The following example demonstrates how to use the Python dictionary type in the C language:

Example 5: typedic. c

// create the dictionaryPyObject* pDict = PyDict_New(); // new referenceassert(PyDict_Check(pDict));// add a few named valuesPyDict_SetItemString(pDict, "first",            Py_BuildValue("i", 2003));PyDict_SetItemString(pDict, "second",            Py_BuildValue("f", 3.14f));// enumerate all named valuesPyObject* pKeys = PyDict_Keys(); // new referencefor(int i = 0; i < PyList_Size(pKeys); ++i) { PyObject *pKey = PyList_GetItem(pKeys, i); PyObject *pValue = PyDict_GetItem(pDict, pKey); assert(pValue);}Py_DECREF(pKeys);// remove a named valuePyDict_DelItemString(pDict, "second");// cleanupPy_DECREF(pDict);
Iii. Python C Language extension
3.1 Module Encapsulation

After learning about the C language interfaces of Python, you can use these interfaces provided by the Python interpreter to compile C language extensions of Python. Assume that the following C language functions are supported:

Example 6: example. c

int fact(int n){ if (n <= 1)   return 1; else   return n * fact(n - 1);}
This function is used to calculate the factorial of a given natural number. If you want to call this function in the Python interpreter, you should first implement it as a module in Python, you need to write the corresponding encapsulation interface as follows:

Example 7: wrap. c

#include <Python.h>PyObject* wrap_fact(PyObject* self, PyObject* args) { int n, result;  if (! PyArg_ParseTuple(args, "i:fact", &n))  return NULL; result = fact(n); return Py_BuildValue("i", result);}static PyMethodDef exampleMethods[] = { {"fact", wrap_fact, METH_VARARGS, "Caculate N!"}, {NULL, NULL}};void initexample() { PyObject* m; m = Py_InitModule("example", exampleMethods);}
A typical Python extension module consists of at least three parts: the export function, method list, and initialization function.
3.2 export functions

To use a function in C language in the Python interpreter, you must first compile the corresponding export function for it. In the preceding example, the export function is wrap_fact. In Python C language extensions, all exported functions have the same function prototype:

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

This function is an interface between the Python interpreter and the C function. It has two parameters: self and args. The self parameter is used only when the C function is implemented as an inline method (built-in method). Generally, the value of this parameter is NULL ). The args parameter contains all the parameters that the Python interpreter must pass to the C function. The Python C Language extension interface provides the PyArg_ParseTuple () function to obtain these parameter values.

All export functions return a PyObject pointer. If the corresponding C function does not return a real value (that is, the return value type is void), a global None object (Py_None) should be returned ), add the reference count to 1, as shown below:

PyObject* method(PyObject *self, PyObject *args) { Py_INCREF(Py_None); return Py_None;}
3.3 method list

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

static PyMethodDef exampleMethods[] = { {"fact", wrap_fact, METH_VARARGS, "Caculate N!"}, {NULL, NULL}};

Each item in the method list consists of four parts: method name, export function, parameter transfer method, and method description. The method name is the name used to call this method from the Python interpreter. The parameter passing method specifies the specific form of passing parameters to the C function in Python. The two optional methods are METH_VARARGS and METH_KEYWORDS. METH_VARARGS is the standard form of parameter passing, it uses the Python tuples to pass parameters between the Python interpreter and the C function. If METH_KEYWORD is used, then, the Python interpreter and the C function will pass parameters between the two through the Python dictionary type.
3.4 initialization Function

All Python extension modules must have an initialization function so that the Python interpreter can correctly initialize the module. The Python interpreter specifies that the names of all initialization functions must start with init and add the module name. For the module example, the corresponding initialization function is:

void initexample() { PyObject* m; m = Py_InitModule("example", exampleMethods);}
When the Python interpreter needs to import the module, it will find the corresponding initialization function based on the module name. Once it is found, it will call the function for initialization, the initialization function registers all the methods available in this module with the Python interpreter by calling the function Py_InitModule () provided by the Python C Language extension interface.
3.5 compilation Link

To use an extension module written in C language in the Python interpreter, it must be compiled into a dynamic link library. The following uses RedHat Linux 8.0 as an example to describe how to compile the Python extension module compiled in C into a dynamic link library:

[xiaowp@gary code]$ gcc -fpic -c -I/usr/include/python2.2 \          -I /usr/lib/python2.2/config \          example.c wrapper.c[xiaowp@gary code]$ gcc -shared -o example.so example.o wrapper.o

3.6 introduce the Python Interpreter

After the dynamic link library of the Python extension module is generated, you can use the extension module in the Python interpreter. This is the same as the Python built-in module, the extension module is also used after being introduced through the import Command, as shown below:

[xiaowp@gary code]$ pythonPython 2.2.1 (#1, Aug 30 2002, 12:15:30)[GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import example>>> example.fact(4)24>>>

Iv. Conclusion

As a powerful scripting language, Python will be more widely used in various fields. To overcome the slow execution speed of the script language, Python provides the corresponding C Language extension interface, which is implemented by using the C language to implement the key code that affects the execution performance, it can greatly improve the speed of running scripts written in Python to meet actual needs.

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.