Shared library file suffix under Linux/unix platform. So; in the Windows platform is called the dynamic link library, the file name suffix is. dll.
Using the cTYPES module to call the C shared library
cTYPES is a module provided by the Python standard library, which is supported by Python version 2.3. cTYPES is a Python advanced external function interface through which Python can invoke a C-language compiled static link library and a dynamic-link library. cTYPES supports multiple platforms, including Windows, Windows CE, Mac OS X, Linux, Solaris, FreeBSD, OpenBSD.
cTYPES module defines some basic C compatible data types, please click here to view the specific types.
The following example shows how to use the cTYPES module in a Python program to invoke a C program function.
1. Prepare the C program source file sum.c
A sum () function is defined in the SUM.C source file to calculate the sum of N contiguous natural numbers.
#include <stdio.h>intMainvoid){ intx; printf ("Input an integer:\n"); scanf ("%d", &x); printf ("sum=%d\n", sum (x)); return 0;};intSumintx) { intI, result=0; for(i=0; i<=x; i++) {result+=i; } returnresult;};
2. Compile the C source code into a shared library file sum.so
Use the GCC compiler to compile SUM.C as a shared library file sum.so.
GCC sum sum. So
3. Preparing the Python module sum.py
In the sum.py module we define a py_sum () function, which is the Python implementation of the sum () function in the Sum.c file.
#!/usr/bin/env python#-*-Coding:utf8-*-ImportCtypesso= cTYPES. Cdll ('./sum.so')defdisplay_dict ():Print "Type of so is%s"%type (SO)Print "Attributes before calling So.sum:%s"%dir (SO)Print "So.sum (Ten) =%s"% So.sum (10) Print "Attributes after calling So.sum:%s"%dir (SO)defpy_sum (x): Y=0 forIinchRange (x+1): Y+=Ireturnydefso_sum (x):returnso.sum (x)if __name__=="__main__": Pass
Import cTYPES in the Python module, and then through cTYPES. The Cdll () method imports the shared library file sum.so and can then invoke the functions provided by the dynamic library directly.
4. Test Python Call Shared library
Let's call the Display_dict function in the __main__ block:
if __name__ " __main__ " : display_dict ()
Run sum.py to see the results:
$ pythonsum. Pytype of So is<class'cTYPES. Cdll'>Attributes before calling so.sum: ['_funcptr','__class__','__delattr__','__dict__','__doc__','__format__','__getattr__','__getattribute__','__getitem__','__hash__','__init__','__module__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__','_func_flags_','_func_restype_','_handle','_name']so.sum(Ten) = -Attributes after calling.sum: ['_funcptr','__class__','__delattr__','__dict__','__doc__','__format__','__getattr__','__getattribute__','__getitem__','__hash__','__init__','__module__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__','_func_flags_','_func_restype_','_handle','_name','sum']
From the results can be found. So shared libraries are imported into the. PY module to get a ctypes. The Cdll object. After the C function is called, the Cdll object adds the function to the object properties. (The SUM function is included in the Cdll object property list after the Sum function is called.) )
5. Python calls the performance of a shared library
Let's modify the sum.py module:
if__name__ = ="__main__": Import Timeit i=10000Print"py_sum (%s) =%s"%(i, Py_sum (i)) print"so_sum (%s) =%s"%(i, So_sum (i)) Print Timeit.timeit ("Py_sum (10000)", setup="From __main__ import py_sum", number= +) Print Timeit.timeit ("So_sum (10000)", setup="From __main__ import so_sum", number= +)
To view the results of a run:
sum . Pypy_sum (1000050005000so_sum (1000050005000 6.820616006850.158802986145
The above tests show that the loop is superimposed 10,000 times, executes the code 1000 times, the Python code takes 6.82 seconds, the C code takes 0.158 seconds, and the Python code consumes 42.95 times times the time of the C code.