A brief analysis of the combination of Python program and C program using _python

Source: Internet
Author: User
Tags exception handling md5 sha1 in python

Python is a programming language for rapid development of software, its syntax is simple, easy to grasp, but there is a slow implementation of problems, and in dealing with some problems, such as access to computer hardware systems, access to media files and so on. As a software development of the traditional programming language C language, but in these problems can be a good way to make up for the lack of Python language. Therefore, this article studies how to integrate the existing C language modules in the Python program, including 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
The characteristics of Python language

Python, as a program development language, is increasingly being applied to rapid program development. Python is an interpretive, interactive, object-oriented programming language that includes modular operations, exception handling, Dynamic Data patterns, and the use of types. Its grammatical expression is beautiful and readable, with many excellent scripting language features: interpreted, object-oriented, built-in advanced data structure, support module and package, support a variety of platforms, scalable. And it also supports interactive mode running, graphical way to run. It has a large number of programming interfaces to support a variety of operating system platforms and a wide range of functional libraries, using C and C + + can be expanded.
the characteristics of C language

As one of the most popular languages, C language has a wide development base. Concise and compact, flexible and convenient, powerful features are its features. In addition, C language is a mid-level language. It combines the basic structure and sentence of high-level language with the practicality of low-level language. Because you can directly access the physical address, you can easily operate the hardware. Therefore, a lot of system software is written by C language.
the interaction between Python language and C language

In order to save software development costs, software developers want to shorten the development time of the software, hope to be able to develop a stable product in a short time. Python is powerful, easy to use, and can quickly develop application software. However, due to the limitations of Python's own execution speed, modules requiring higher performance requirements need to be developed using more efficient programming languages, such as C, other modules of the system using Python for rapid development, and finally the modules developed by C language are integrated with the modules developed by Python. In this context, based on the characteristics of Python language and C language, it is meaningful to extend the existing Python program with C language. This paper first introduces several common methods of integrating Python program with C language program, and finally gives the corresponding example.
Using the cTYPES module to integrate Python programs and C programs
ctypes Module

cTYPES is a standard module of Python, which is included in Python2.3 and above versions. cTYPES is a Python advanced external function interface that enables Python programs to invoke static link libraries and dynamic link libraries compiled by C language. Using the cTYPES module, you can create, access, and manipulate simple or complex C-language data types in a Python source program. Most importantly, the cTYPES module is able to work on multiple platforms, including Windows,windows Ce,mac OS X,linux,solaris,freebsd,openbsd.

Let's take a few simple examples to see how the cTYPES module consolidates Python programs and C programs.
consolidation at the source code 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 variables similar to the C language in a Python program by using the cTYPES library.

The following table lists the cTYPES variable types, the relationship between the C language variable type and the Python language variable type:
table 1. Ctypes,c language and Python language variable type relations

The first column in table 1 is the variable type defined in the cTYPES library, the second column is the variant type defined by the C language, and the third column is the variant type defined by the Python language when the ctypes is not used.

Example:
Listing 1. cTYPES Simple to use

 >>> from ctypes Import *        # Imports cTYPES Library All modules
 >>> i = C_int ()            # define an int variable with a value of 
 >& gt;> i.value                # Print variable value 
 >>> i.value =             # Change the value of the variable to 
 >>> i.value                # New value for print variable
 56

The following example shows a more obvious similarity between variable types in ctypes and types of C-language variables:
Listing 2. cTYPES uses the C language variable

 >>> p = create_string_buffer   A variable string variable with a length of 
 >>> P.raw                 # The initial value is all 0, that is, the string terminator in C language ' \ 0 '
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 '
 >>> p.value = ' Student '         # string Assignment
 >> > P.raw                 # Three characters are still '
student\x00\x00\x00 '
 >>> p.value = ' big '           # re assigned to
 >> > P.raw                  # Only the first three characters were modified, and the fourth character was modified to '
big\x00ent\x00\x00\x00 '

The following example illustrates the pointer operation:
Listing 3. cTYPES uses the C language pointer

 >>> 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                   # Print What the pointer refers to
 c_long (999) 
 >>> pi.contents = c_long (1000)          # Change the value of the variable i by pointer c26/>>>> pi.contents                   # Print What the pointer refers to
 c_long (1000)

The following example illustrates the structure and array operations:
Listing 4. cTYPES uses the C language array and the struct body

 >>> 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 point type variable with an initial value of x=2, y=5 
 >>> print point.x, point.y           # Print variable C12/>2 5 
 >>> point = Point (y=5)              # Redefine a point type variable, x take the default value
 >>> print Point.x, Point.y
   # Print variable
 0 5 
 >>> point_array = point * 3          # defines the array type Point_array for Point
 # defines a point array that contains three Point variable
 >>> pa = Point_array (Point (7, 7), point (8, 8), point (9, 9)) 
 >>> to P in Pa:print p . x, p.y        # Prints the value of each member in the point array
 ... 
 7 7 
 8 8 
 9 9

Python access to the C language DLL

Using the cTYPES module, the Python program can access the DLL compiled by C language, and this section describes how the Python program calls the HelloWorld function in Some.dll in a simple example, in the Python program helloworld.py. DLLs on the Windows platform.

Import a dynamic link library
Listing 5. cTYPES Import DLL

 From ctypes import Windll # First import the Windll sub module of the cTYPES module
 somelibc = Windll. LoadLibrary (Some.dll) # using LoadLibrary of Windll modules to import dynamic link libraries

Accessing functions in a dynamic link library
Listing 6. cTYPES using a function in a DLL

SOMELIBC. HelloWorld () # So you can get the return value of Some.dll HelloWorld.

The whole helloworld.py is like 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 ()

Running helloworld.py at the command line, you can see the output of HelloWorld in Some.dll on the console.
Listing 8. Python hellpworld Windows Command Console to run output

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

Python calls the C language so

With the cTYPES module, Python programs can also access the so file compiled by the C language. The method of calling C's DLL in Python is essentially the same, and this section describes how the Python program invokes the Linux platform by invoking the HelloWorld function in some.so in the Python program helloworld.py in a simple example. So

Import a dynamic link library
Listing 9. cTYPES Import So

 From ctypes import Cdll   
   # First import the Cdll sub module of the cTYPES module and note that Cdll is used on the Linux platform instead of Windll.
   somelibc = Cdll. LoadLibrary ("./some.so")
   # import dynamic link library using LoadLibrary of Cdll module

accessing functions in a dynamic link library
Listing 10. cTYPES using functions in so

   SOMELIBC. HelloWorld () # uses the same method as the Windows platform.

The whole helloworld.py is like 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 ()

Running helloworld.py on the command line, 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

Here's an example of using Python to implement a small tool to implement the hash algorithm, view the file checksum (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 to "hash", is the arbitrary length of the input (also known as the pre-image), through hashing algorithm, transform into a fixed length of output, the output is hash value. This conversion is a compression map, in which the space of the hash value is usually much smaller than the input space, and different inputs may be hashed out into the same output, and it is not possible to uniquely determine the input value from the hash value. Simply put, a function that compresses messages of any length into a message digest of a fixed length.

Because Python is less efficient than the C language, our Python gadget implements our program using an existing C-language dynamic link library (hashtcalc.dll). In this case, we use WxPython to write a simple GUI interface, call the Hashtcalc.dll interface through Python to compute the checksum of the file, and then output it in the interface.
Frame composition
Figure 1. Schema 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: This function evaluates 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: This function evaluates 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: This function evaluates the contents of the input file and returns its SHA1
Hashcalcadapter Code

hashcalcadapter.py implements a Python class Hashcalcadapter,hashcalcadapter encapsulates the C language interface of HASHTCALC.DL, allowing other Python modules to go directly through the 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): C4/>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 the interface
Figure 2. The running interface of the tool

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.