python调用C
1. 文件目录为
./
add.c
python-c.py
2. 进入文件目录编译成dll库
cygwin下执行:gcc -shared -Wl,-soname,adder -o adder.dll -fPIC add.c
3. 运行python代码
import ctypes
#load the shared object file
adder = ctypes.cdll.LoadLibrary('adder.dll')
#Find sum of integers
res_int = adder.add_int(4,5)
print("4 + 5 = " + str(res_int))
#Find sum of floats
a = ctypes.c_float(5.5)
b = ctypes.c_float(4.1)
add_float = adder.add_float
add_float.restype = ctypes.c_float
print("5.5 + 4.1 = " + str(add_float(a, b)))
4. 注意运行int和float不同的处理方式
adder.add_int(4,5)
add_float(a, b)