The ctypes module in Python is probably the easiest one of Python's calls to C methods. The ctypes module provides data types and functions compatible with C language to load the dll file, so no modifications to the source file are required when calling. This is also the simplicity of this approach.
The example is as follows
Implement the C code to sum two numbers, save as
//sample C file to add 2 numbers - int and floats #include <> int add_int(int, int); float add_float(float, float); int add_int(int num1, int num2){ return num1 + num2; } float add_float(float num1, float num2){ return num1 + num2; }
Next, compile the C file into a .so file (DLL under Windows). The following operation will generate a file
#For Linux $ gcc -shared -Wl,-soname,adder -o -fPIC #For Mac $ gcc -shared -Wl,-install_name, -o -fPIC #For windows $ gcc -shared -Wl,-soname,adder -o -fPIC
Now call it in your Python code
from ctypes import * #load the shared object file adder = CDLL('./') #Find sum of integers res_int = adder.add_int(4,5) print "Sum of 4 and 5 = " + str(res_int) #Find sum of floats a = c_float(5.5) b = c_float(4.1) add_float = adder.add_float add_float.restype = c_float print "Sum of 5.5 and 4.1 = ", str(add_float(a, b))
The output is as follows
Sum of 4 and 5 = 9
Sum of 5.5 and 4.1 = 9.60000038147
In this example, the C file is self-interpreted, which contains two functions that implement the shaping sum and floating point sum.
In a Python file, first import the ctypes module, and then use the CDLL function to load the library file we created. In this way, we can use the functions in the C library through the variable adder. When add.add_int() is called, a call to the C function add_int will be initiated internally. The ctypes interface allows us to use the default string and integer types in native Python when calling C functions.
For other types like Boolean and Floating Point, the correct ctype type must be used. For example, when passing arguments to the adder.add_float() function, we must first convert the decimal value in Python to the c_float type before passing it to the C function. Although this method is simple and clear, it is very limited. For example, objects cannot be operated in C.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.