程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Advanced Series (14)

編輯:Python

Python/C API

Python/C API Probably the most widely used method . It's not just simple , And it can be in C Operate your... In code Python object .

This method needs to be written in a specific way C Code for Python To call it . be-all Python Objects are represented as a form called PyObject The structure of the body , also Python.h The header file provides various functions to operate it . for example , If PyObject Expressed as PyListType( List the type ) when , Then we can use PyList_Size() Function to get the length of the structure , similar Python Medium len(list) function . Most of them are right Python The basic functions and operations of native objects are Python.h Can be found in the header file .

Example

Write a C Expand , Add all elements to one Python list ( All elements are numbers )

Let's see what we want to achieve , Here is a demonstration of using Python call C Extended code

Though it looks like an ordinary python import, the addList module #is implemented

import addList

l = [1,2,3,4,5]
print "Sum of List - " + str(l) + " = " + str(addList.add(l))

The above code is similar to the ordinary Python Documents are no different , Imported and used another one called addList Of Python modular . The only difference is that this module does not use Python Compiling , It is C.

Next let's see how to use C To write addList modular , This may seem a little unacceptable , But once you understand the various components , You can move forward .


//Python.h has all the required function definitions to manipulate the Python #include <Python.h>
//This is the function that is called from your python code
static PyObject* addList_add(PyObject* self, PyObject* args){
PyObject * listObj;
//The input arguments come as a tuple, we parse the args to get //the various
//In this case it's only one list variable, which will now be //referenced
if (! PyArg_ParseTuple( args, "O", &listObj ))
return NULL;
//length of the list
long length = PyList_Size(listObj);
//iterate over all the elements
int i, sum =0;
for (i = 0; i < length; i++) {
//get an element out of the list - the element is also a //python objects
PyObject* temp = PyList_GetItem(listObj, i);
//we know that object represents an integer - so convert it //into C
long elem = PyInt_AsLong(temp);
sum += elem;
}
//value returned back to python code - another python object
//build value here converts the C long to a python integer
return Py_BuildValue("i", sum);
}
//This is the docstring that corresponds to our 'add' function.
static char addList_docs[] ="add( ): add all elements of the list\n";
/* This table contains the relavent info mapping -
<function-name in python module>, <actual-function>,
<type-of-args the function expects>, <docstring associated with the function>
*/
static PyMethodDef addList_funcs[] = {
{"add", (PyCFunction)addList_add, METH_VARARGS, addList_docs},
{NULL, NULL, 0, NULL}
};
/*
addList is the module name, and this is the initialization block of the <desired module name>, <the-info-table>, <module's-docstring>
*/
PyMODINIT_FUNC initaddList(void){
Py_InitModule3("addList", addList_funcs, "Add all ze lists");
}

Step by step

  1. Python.h The header file contains all the required types (Python Representation of object type ) And function definition ( Yes Python Operations on objects )
  2. Next, we will write in Python Called function , The traditional naming method of functions is { Module name }_{ Function name } form , So we call it addList_add
  3. Then fill in the relevant information table of the function you want to implement in the module , One function per line , End with a blank line
  4. The final module initialization block signature is PyMODINIT_FUNC init{ Module name }.

function addList_add The accepted parameter type is PyObject Type structure ( It is also expressed as tuple type , because Python All things are objects , So let's use PyObject To define ). The passed in parameters are passed through PyArg_ParseTuple() Parsing . The first parameter is the parsed parameter variable . The second parameter is a string , Tell us how to parse every element in a tuple . String number n The first letter represents the second letter in the tuple n Types of parameters . for example ,"i" For plastic surgery ,"s" Represents the string type , "O" Represents a Python object . The next parameters are all you want to pass

too PyArg_ParseTuple() Function to parse and save the element . In this way, the number of parameters can be consistent with the number of parameters expected by the function in the module , And ensure the integrity of the location . for example , We want to pass in a string , An integer and a Python list , You can write like this


int n;
char *s;
PyObject* list;
PyArg_ParseTuple(args, "siO", &n, &s, &list);

under these circumstances , We just need to extract a list object , And store it in listObj variable . Then use... In the list object PyList_Size() Function to get its length . It's like Python Call in len(list).

Now let's go through the loop list , Use PyList_GetItem(list, index) Function to get each element .

This will return to a PyObject* object . since Python Objects can also represent PyIntType, We just use PyInt_AsLong(PyObj *) Function to get the value we need . We do this for every element , Finally, we get the sum of them .

The sum will be converted into a Python Object and pass Py_BuildValue() Return to Python Code , there i Indicates that we want to return a Python Shaping object .

Now we have written C Module . Save the following code as setup.py


#build the modules
from distutils.core import setup, Extension
setup(name='addList', version='1.0', \
ext_modules=[Extension('addList', ['adder.c'])])

And run

python setup.py install

By now, we should have C File compilation and installation into our Python Module .

After a lot of hard work , Let's verify whether our module is effective


#module that talks to the C code
import addList
l = [1,2,3,4,5]
print "Sum of List - " + str(l) + " = " + str(addList.add(l))

The output is as follows

Sum of List - [1, 2, 3, 4, 5] = 15

As you can see , We've used Python.h API Successfully developed our first Python C Expand . This approach seems complicated , But once you get used to it , It will become very effective .

Python call C Another way to code is to use Cython Give Way Python Compile faster . however Cython And traditional Python In comparison, it can be understood as another language , So we won't describe it too much here .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved