To analyze the use of Python programs in conjunction with C programs

Source: Internet
Author: User
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 C language of software development, it 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.
Overview

Introduction to Background knowledge
Features of the 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.
Using the cTYPES module to integrate Python programs and C programs
cTYPES Module

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

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)                 # define INT type variable i, value 999  >>> PI = pointer (i)                # define pointer, point to variable i  >>&G T Pi.contents                   # Prints What the pointer refers to C_long (999)  >>> pi.contents = C_long (#)          # Change the value of the variable i by the pointer >>> Pi.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  >>> Point_array = point * 3          # defines Point_array as the array type for point # defines a point array containing three point variables >>> PA = Point_array (Point (7, 7), point (8, 8), point (9, 9))  >>> as P in Pa:print p.x, p.y        # Prints the point array for each The value  of a 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 a dynamic-link library
Listing 5. cTYPES Import DLL

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

Accessing 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 Code

   From 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 output

   C:\>python C:\python\test\helloworld.py    Hello world! Just a simple test.

Python calls C language so

With the cTYPES module, the Python program can also access 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 a 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

accessing 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 Code

   From 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

   [root@linux-790t] python./helloworld.py    Hello world! Just a simple test.

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.
Architecture diagram
Figure 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): C5/>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)

Run interface
Figure 2. The tool's running interface

  • 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.