First, write a library of functions in C language.
#include <stdio.h>int Add (int num1, int num2) {return num1 + num2;} int sub (int num1, int num2) {return num1-num2;} int mul (int num1, int num2) {return NUM1 * NUM2;} int div (int num1, int num2) {return num1/num2;}
Second, then use GCC to compile into a static library
Gcc-c-fpic math.cgcc-shared Math.o-o math.so
Third, import the static library using the Python ctypes library
#!/opt/python3/bin/python3#from ctypes Import *import osprint ("Begin ...") Libmathpath = Os.path.join (OS.GETCWD (), " Math.so ") print (libmathpath) Libmath = Cdll (libmathpath) print ("-----------------") print (" add:21 ") print ( Libmath.add (21,89)) print ("-----------------") print ("sub:124") Print (Libmath.sub (123,89)) print ("-------------- ---") print (" Mul:12 ") Print (Libmath.mul (12,77)) print ("-----------------") Print (" div:183 3 ") Print (Libmath.div ( 183,3)) Print ("-----------------")
4, the execution results are as follows:
Begin .../home/git/math.so-----------------add:21 89110-----------------sub:124 8934-----------------mul:12 77924-----------------div:183 361-----------------
1 (math.c source)
2 (testmath.py) source code
3 (Perform the investigation)
A function that calls the C language in Python3