Python ctypes, pythonctypes
In recent days, we have used python to interact with c/c ++ programs. swig is recommended on the Internet, but the effect is not satisfactory. Therefore, we have pondered the python ctypes module. At the same time, although there is content in this area on the internet, I still don't think it is clear. The record is used for backup, and it is also convenient for the majority of python with c/c ++. If you think I am not writing well, you canRefer to official documentationThe introduction of ctypes, which says there is not necessarily what you want.
If any error occurs, correct it :).
Test environment: win 8.1, Visual Studio 2010, Python 3.5
I. Introduction
Python interacts with c/c ++ for the purpose of speed and script.
Python interacts with c/c ++, but python interacts with c because python only supports C APIs. However, we can achieve python and c ++ project collaboration through adjustment. The following describes the main points and difficulties for python to use the ctypes module to interact with c.
2. What can I do with ctypes?
Python can call c functions by using the ctypes module, which must include variable types (including struct and pointer types) that can be defined in c ).
The official definition is"ctypesIs a foreign function library for Python. it provides C compatible data types, and allows calling functions in DLLs or shared libraries. it can be used to wrap these libraries in pure Python. "-- introduced from the Python 3.5 chm document. The general idea is -- ctypes is an external function library for Python. It provides data types compatible with C and allows you to call functions in a DLL or shared library. With this function, you can use pure Python to wrap these function libraries (so that you can directly import xxx to use these function libraries ).
We need a specific example. We will introduce a cpp file to illustrate all the following problems:
The existing test. cpp file is as follows:
# If 1 # define DLL_API _ declspec (dllexport) # else # define DLL_API _ declspec (dllimport) # endif # include <stdio. h> # include <stdlib. h> // Point struct Point {float x, y ;}; static Point * position = NULL; extern "C" {DLL_API int add (int a, int B) {return a + B;} DLL_API float addf (float a, float B) {return a + B;} DLL_API void print_point (Point * p) {if (p) printf ("position x % f y % f", p-> x, p-> y );}}
We can see that there are three functions, including a function with a pointer. Learning to use Python to successfully call the above three functions is my goal in this article. For windows platforms, you can generate a dll file (other platforms are. so ). Next we will write the Python code for testing in the interpreter.
If you do not understand the cpp File above, read other dll articles first:
1. Dll analysis and writing (1) http://www.cnblogs.com/hicjiajia/archive/2010/08/27/1809997.html
2. Use of extern "C" to parse http://www.cnblogs.com/rollenholt/archive/2012/03/20/2409046.html
3. How does ctypes call c's function library?
First, ctypes is required to load the function library to be called (nonsense ).
Use ctypes. CDLL, which is defined as follows (derived from the Python 3.5 chm document)
ctypes. CDLL( Name, Mode = DEFAULT_MODE, Handle = None, Use_errno = False, Use_last_error = False)
In addition, the modes parameter is ignored on windows. For windows platforms, you can also call ctypes. WinDLL, which is almost the same as the above CDLL. The only difference is that it assumes that the functions in the library follow the Windows stdcall call conventions. For the meanings of other parameters, see the official documentation.
If you wantCall the add function in test. dll.Writability:
>>> From ctypes import * >>> dll = CDLL ("test. dll) # Call test. dll >>> dll. add (10, 30) # Call the add function 40
We can see that 40 is returned, isn't it easy ?. This is what we expected. Next, we will call addf. This is the float version of add. Some may ask why not write the DLL_API float add (float a, float B) directly )? Just use the function overload. Why not do this? Note: The extern "C" clause is used to declare a function. Therefore, function Overloading is not supported.
Next we will call addf to guess what will happen?
>>> dll.addf(10, 30)9108284
Oh, isn't that unexpected? Why?
IV. c and Python types, parameter types, and return types
The reason why the addf function is called "failed" is not a problem with Python. The reason is that you didn't "tell" the "appearance" of the Python function (more formally speaking, "Description")-the type of the function's form parameter and return type. So why did we call add successfully? The default parameter type and return type of Python functions are int type. Python assumes that addf returns an int value.
That is to say, when ctypes reads the dll, it only knows that this function exists, but does not know the type of the function's form parameter and return value. You may wonder why Python is so troublesome and tell it the "appearance" of functions in the shared library ". In fact, the C # language developed by Microsoft needs to tell C # What the function looks like when calling the dll. This is a bit annoying to explain. Let's focus on our research on the usage of ctypes.
So what types of c are available for Python? The following is a table of c type corresponding to the type in Python (from the Python 3.5 chm document)
Then, how can we tell Python the type of the form parameter of an external function and the type of the returned value?
This requires assigning values to the restype and argtypes attributes of the function.They correspond to the return type and parameter type respectively. The Return Value Type of addf is float, which corresponds to c_float in Python. Next we will assign values:
>>> Dll. addf. restype = c_float # The type of addf returned value is flaot.
If the return value of the function is void, you can assign a value of None. In versions that are not too low, you can use the Python built-in type (the rightmost column in the table) to "describe" The return type of the library function. However, you cannot use Python built-in types to describe the parameters of library functions.
Because the number of function parameters is not fixed, you need to use the list or tuples to describe them:
>>> Dll. addf. argtypes = (c_float, c_float) # addf has two parameters, both of which are of the float type or below. However, you know, the efficiency of searching tuples is slightly higher :) >>> dll. addf. argtypes = [c_float, c_float] # addf has two parameters of the float type.
After all the work is done, call addf again:
>>> dll.addf(8, 3)11.0>>> dll.addf(8.3, 3.1)11.399999618530273
This is what we want.
V. Create and use the ctypes type more
We can also create a ctypes type (c_int, c_float, c_char ......) Assign a value to him, for example:
>>> I = c_int (45) # define an int variable with a value of 45 >>> I. value # print the variable value 45 >>> I. value = 56 # change the variable value to 56 >>> I. value # print the new value of the variable 56
Yes, you have to use the ctypesValue AttributeAssign a value to a ctypes type -- assign a value of the Python built-in type.
Other ctypes functions, such as sizeof (I) (is it very considerate like c), will not be described one by one. For more information, see article 3 and official documents.
Vi. struct and shared body
This is one of the necessary components to call the print_point library function.
If you want to define a c-type struct in Python, You need to define a class, such as Structu Point:
>>> class Point(Structure):... _fields_ = [("x", c_float), ("y", c_float)]...>>>
This is defined. There are two key points:
1. The class must inherit from ctypes. Structure
2. Describe the "appearance" of this struct"
The first point is very simple. class XXX (Structure) is OK.
To achieve the second goal, you must define an attribute named _ fields _ in the Custom c struct class and assign it to the above list.
Then you can use it like this:
>>> P = Point () # defines a Point-type variable. The initial value is x = 2 and y = 5. You can also directly write p = Point () >>> p. y = 3 # modify the value >>> print (p. x, p. y) # print variable 2 3
For a shared object, as long as the class inherits from ctypes. Union, the others are the same as those above.
VII. pointer
This is the last section. Although it is a pointer, don't be nervous and listen to me.
How to Create a ctypes pointer? Here there are three functions in ctypes with pointers, and you will naturally understand them (maybe pointer POINTER will be a little round, just take a closer look ).
| Function |
Description |
| Byref (x [, offset]) |
Returns the address of x. x must be an instance of the ctypes type. It is equivalent to c & x. Offset indicates the offset. |
| Pointer (x) |
Create and return a pointer to x. x is an instance object. |
| POINTER (type) |
Returns a type, which is a pointer type pointing to the type, and type is a type of ctypes. |
Byref is easy to understand. This is used when passing parameters. You can also use pointer to create a pointer variable, but byref is faster.
The difference between pointer and POINTER is that pointer returns an instance and POINTER returns a type. You can even use POINTER to do pointer's work:
>>> A = c_int (66) # create a c_int instance >>> B = pointer (a) # create a POINTER >>> c = pointer (c_int) () # create a pointer >>> B <__ main __. LP_c_long object at 0x00E12AD0 >>> c <__ main __. LP_c_long object at 0x00E12B20 >>> B. contents # output the value of a c_long (66) >>> c. contents # output the value of a c_long (66)
The pointer created by pointer does not seem to have a way to modify the ctypes type value.
I have already said everything. Next I will call the print_point function:
>>> Dll. print_point.argtypes = (POINTER (Point),) # specify the parameter type of the function> dll. print_point.restype = None # specify the function return type >>>>>> p = Point (32.4,-92.1) # instantiate a Point >>> dll. print_point (byref (p) # Call the position x 32.400002 y-92.099998 function >>>
Of course you have to use a slower pointer:
>>> Dll. print_point (pointer (p) # Call the position x 32.400002 y-92.099998 function >>>
The result is what we want :)
As for why there is a malformed "y-92.099998 >>>" behind the output, you will find it by turning the c code above.
References