http://www.ibm.com/developerworks/cn/linux/l-cn-pythonandc/
Overview
Python is a programming language for the rapid development of software, its syntax is relatively simple, easy to grasp, but there are slow execution problems, and in dealing with some problems, such as access to computer hardware systems, access to media files, and so on. As the traditional programming language of software development,--C language can make up for the lack of Python language in these problems. Therefore, this paper studies how to integrate the existing C language module in Python program, including the source program and dynamic link library written in C language, so as to give full play to the advantages of Python language and C language.
Back to top of page
Background information on the characteristics of Python language
As a programming language, Python is increasingly being used for rapid program development. Python is an interpretive, interactive, object-oriented programming language that contains modular operations, exception handling, Dynamic Data forms, and the use of types. Its syntax is beautifully readable and features many excellent scripting languages: interpreted, object-oriented, built-in advanced data structures, support modules and packages, support for multiple platforms, extensible. It also supports interactive mode running and graphical operation. It has a wide range of programming interfaces to support a variety of operating system platforms as well as a wide variety of function libraries, which can be augmented with C and C + +.
Features of C language
As one of the most popular languages, C language has a broad development base. Simple and compact, flexible and convenient, powerful is its features. In addition, C language is an intermediate language. It combines the basic structures and statements of high-level languages with the practicality of low-level languages. Because the physical address can be accessed directly, the hardware can be easily manipulated. Therefore, a lot of system software is written in C language.
The Python language interacts with the C language
To save software development costs, software developers want to shorten the development time of the software, hoping to develop a stable product in a short period of time. Python is powerful, easy-to-use, and fast to develop application software. However, due to the limitations of Python's own execution speed, modules with higher performance requirements need to be developed using more efficient programming languages, such as C, where other modules of the system are developed quickly using Python, and the modules developed by the C language are integrated with those developed by Python. In this context, based on the Python language and C language of their respective characteristics, C language to expand the existing Python program, it seems very meaningful. This paper first introduces several common methods of integrating Python program with C language program, and finally gives corresponding examples.
Back to top of page
Integrating Python programs and C program cTYPES modules with cTYPES modules
cTYPES is a standard Python module that is included in the Python2.3 and above versions. cTYPES is a Python advanced external function interface that enables Python programs to invoke C-language compiled static-link libraries and dynamic-link libraries. Using the cTYPES module, you can create, access, and manipulate simple or complex C-language data types in Python source programs. Most importantly, the cTYPES module is capable of working on multiple platforms, including Windows,windows Ce,mac OS X,linux,solaris,freebsd,openbsd.
Let's take a look at some simple examples of how the cTYPES module integrates Python programs and C programs.
Integration at the source level
Using the cTYPES module provided by Python itself enables the Python language and C language to be integrated at the source level. This section describes how you can define C-like variables in a Python program by using the cTYPES library.
The following table lists the relationships between the cTYPES variable type, the C language variable type, and the Python language variable type:
Table 1. Ctypes,c language and Python language variable type relationships
| ctypes Type |
C type |
Python Type |
| C_char |
Char |
1-character string |
| C_wchar |
wchar_t |
1-character Unicode string |
| C_byte |
Char |
Int/long |
| C_ubyte |
unsigned char |
Int/long |
| C_short |
Short |
Int/long |
| C_ushort |
unsigned short |
Int/long |
| C_int |
Int |
Int/long |
| C_uint |
unsigned int |
Int/long |
| C_long |
Long |
Int/long |
| C_ulong |
unsigned long |
Int/long |
| C_longlong |
__int64 or Long Long |
Int/long |
| C_ulonglong |
Unsigned __int64 or unsigned long long |
Int/long |
| C_float |
Float |
Float |
| C_double |
Double |
Float |
| C_char_p |
char * (NUL terminated) |
String or None |
| C_wchar_p |
wchar_t * (NUL terminated) |
Unicode or None |
| C_void_p |
void * |
Int/long or None |
The first column in table 1 is the variable type defined in the cTYPES library, the second column is the variable type defined by the C language, and the third column is the variable type that the Python language defines when it is not using ctypes.
Example:
Listing 1. cTYPES Simple to use
>>> from ctypes Import * # Imports all modules in cTYPES library >>> i = C_int ($) # defines an int variable with a value of $ >>& Gt I.value # The value of the print variable >>> i.value = # # # Change the value of the variable to the new value of the I.value # print Variable 56
The following example shows a more obvious similarity between the variable type in ctypes and the type of C variable:
Listing 2. cTYPES using C-language variables
>>> p = create_string_buffer (Ten) # defines a variable string variable with a length of ten >>> P.raw # The initial value is all 0, which is the string terminator in the C language ' \ 0 ' \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 ' >>> p.value = ' Student ' # string Assignment >>> P.raw # The last three characters are still ' student\x00\x00\x00 ' >>> p.value = "Big" # re-assigned >>> P.raw # Only the first three characters are modified, The fourth character was modified to ' big\x00ent\x00\x00\x00 '
The following example illustrates the pointer operation:
Listing 3. cTYPES using C language pointers
>>> i = c_int (999) # defines the int type variable i, the value is 999 >>> PI = pointer (i) # defines the pointer, pointing to the variable i >>> Pi.contents # Prints What the pointer refers to C_long (999) >>> pi.contents = C_long (#) # Change the value of the variable i >>> pi through the pointer. Contents # Print What the pointer refers to C_long (1000)
The following example illustrates the structure and array operations:
Listing 4. cTYPES using C-language arrays and structs
>>> class Point (Structure): # Defines a structure that contains two member variables x, y, all int ... _fields_ = [("X", C_int), ... ("Y", C_int)] ... >>> point = Point (2,5) # defines a variable of point type with an initial value of x=2, y=5 >>> print point.x, point.y # print Variable 2 5 >>> point = Point (y=5) # Redefine a point type variable, X takes default value >>> print Point.x, point.y # prints variable 0 5< c12/>>>> Point_array = point * 3 # defines an array type of Point_array for point # Defines a point array containing three point variables >>> p A = Point_array (Point (7, 7), point (8, 8), point (9, 9)) >>> as P in Pa:print p.x, p.y # Prints each in the point array The value of the member ... 7 7 8 8 9 9
Python accesses C language DLLs
Through the cTYPES module, the Python program can access the C language compiled DLL, this section through a simple example, Python program helloworld.py in Some.dll HelloWorld function, to describe how the Python program calls DLLs on the Windows platform.
- Import the dynamic link library Listing 5. cTYPES Importing DLLs
From ctypes import Windll # First, the windll submodule somelibc = Windll of the cTYPES module is imported. LoadLibrary (Some.dll) # import the dynamic-link library using the LoadLibrary of the Windll module
- To access the functions in the dynamic link library, listing 6. cTYPES using functions in a DLL
SOMELIBC. HelloWorld () # So you can get the return value of Some.dll HelloWorld.
The whole helloworld.py is this:
Listing 7. Python Hellpworld CodeFrom ctypes import Windll def CALLC (): # Load the some.dll somelibc = Windll. LoadLibrary (some.dll) print somelibc. HelloWorld () if __name__== "__main__": CALLC ()
Run helloworld.py on the command line and you can see the output of HelloWorld in Some.dll on the console.
Listing 8. Python hellpworld Windows Command Console run outputC:\>python C:\python\test\helloworld.py Hello world! Just a simple test.
Python calls C language so
The
Through the cTYPES module, the Python program also has access to the C language compiled so file. The method of invoking C's DLL with Python is basically the same, and this section uses a simple example of a Python program called the HelloWorld function in some.so to describe how the Python program calls the helloworld.py on the Linux platform. So
- Import the dynamic link library listing 9. cTYPES Import So
From ctypes import Cdll # First import the Cdll submodule of the cTYPES module, note that the Linux platform uses Cdll instead of Windll. SOMELIBC = Cdll. LoadLibrary ("./some.so") # import the dynamic-link library using the LoadLibrary of the Cdll module
- To access the functions in the dynamic link library, listing 10. cTYPES using the functions in so
SOMELIBC. HelloWorld () # Use the same method as on the Windows platform.
The whole helloworld.py is this:
Listing 11. Python HelloWorld CodeFrom ctypes import Cdll def CALLC (): # Load the some.so somelibc = Cdll. LoadLibrary (some.so) print somelibc. HelloWorld () if __name__== "__main__": CALLC ()
Run helloworld.py on the command line and you can see the output of HelloWorld in some.so on the Linux standard output.
Listing 12. Python hellpworld Linux Shell Run output[[email protected]] python./helloworld.py Hello world! Just a simple test.
Back to top of page
Python programs and C program consolidation examples
The following example uses Python to implement a gadget that implements a hash algorithm to view the checksum of a file (MD5,CRC,SHA1, and so on). By viewing the checksum of a file, you can know whether the file was corrupted or tampered with during transmission.
Hash, the general translation to do "hash", there is a direct transliteration of "hash", is the arbitrary length of the input (also known as pre-mapping, pre-image), through the hash algorithm, transformed into a fixed-length output, the output is the hash value. This conversion is a compression map, that is, the space of the hash value is usually much smaller than the input space, the different inputs may be hashed to the same output, but not from the hash value to uniquely determine the input value. Simply, a function that compresses messages of any length to a message digest of a fixed length.
Because Python is less efficient than the C language, our Python gadget uses an existing C-language dynamic-link library (Hashtcalc.dll) to implement our program. In this example, we use WxPython to write a simple GUI interface that uses Python to call Hashtcalc.dll's interface to calculate the checksum of the file and then output it on the interface.
Schema diagram 1. Structure diagram of the tool
Hashcalc.dll Interface Description
Function Name: CALC_CRC32
Function: char* calc_crc32 (char *filename);
Parameters: File name
return value: String
Description: The function computes the contents of the input file and returns its CRC32
Function Name: CALC_MD5
Function: char* calc_md5 (char *filename);
Parameters: File name
return value: String
Description: The function computes the contents of the input file and returns its MD5
Function Name: CALC_SHA1
Function: char* calc_sha1 (char *filename);
Parameters: File name
return value: String
Description: The function computes the contents of the input file and returns its SHA1
Hashcalcadapter Code
hashcalcadapter.py implements a Python class hashcalcadapter,hashcalcadapter that encapsulates the C-language interface of HASHTCALC.DL, allowing other Python modules to be directly Hashcalcadapter uses the hash algorithm implemented in Hashtcalc.dll. The specific code is as follows:
Listing 13. hashcalcadapter.py Code
From ctypes import Windll from ctypes Import * class Hashcalcadapter (object): def __init__ (self, DllPath): C3/>self._dllpath = DllPath self._libc = Windll. LoadLibrary (Self._dllpath) def calc_crc32 (self, filename): new_filename = c_char_p (filename) return SELF._LIBC.CALC_CRC32 (new_filename) def calc_md5 (self, filename): new_filename = c_char_p (filename) Return Self._libc.calc_md5 (new_filename) def calc_sha1 (self, filename): new_filename = c_char_p (filename) return SELF._LIBC.CALC_SHA1 (new_filename)
Operating interface Figure 2. The tool's running interface
Back to top of page
Summarize
In the process of software development, both Python language and C language can be used to speed up the development and to ensure the performance of the software.
On the integration of Python program and C Program (reproduced)