python ctypes调用C函数
python可以用ctypes库调用C函数
1.生成.dll(windows下)或.so(linux下)文件
//pycall.c
#include <stdio.h> #include <stdlib.h> int foo(int a, int b)
{
printf("you input %d and %d\n", a, b);
return a+b;
}
#For Windows
生成dll文件.
gcc -Wall -shared pycall.c -o pycall.dll
或者
gcc --share pycall.c -o pycall.dll
#For Linux
生成so文件.
gcc -o pycall.so -shared -fPIC pycall.c
#For Mac
gcc -shared -Wl,-install_name,adder.so -o adder.so -fPIC add.c
2.ctypes调用
#下面是加载dll方法:
#stdcall调用约定:两种加载方式 :Objdll = ctypes.windll.LoadLibrary("dllpath")和Objdll = ctypes.WinDLL("dllpath")
#cdecl调用约定:也有两种加载方式:Objdll = ctypes.cdll.LoadLibrary("dllpath")和Objdll = ctypes.CDLL("dllpath")
import ctypes #1 ll = ctypes.cdll.LoadLibrary("./pycall.so") ll1=ctypes.cdll.LoadLibrary("./pycall.dll") #2 ll3=ctypes.windll.LoadLibrary("./pycall.so") ll4=ctypes.WinDLL("./pycall.dll") #3 ll5=ctypes.CDLL("./pycall.so") ll6=ctypes.CDLL("./pycall.dll") ll1.foo(2,4) ll3.foo(5,6) ll4.foo(7,8) ll5.foo(9,10) ll6.foo(11,12) print( '***finish***')
***finish*** you input 2 and 4 you input 5 and 6 you input 7 and 8 you input 9 and 10 you input 11 and 12