在python中调用C/C++需要通过gcc将“.c”文件生成“.dll”文件,然后python调用这个文件
1、这里的c文件如下图所示:
#include <stdio.h>
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;
}
2、转换的命令如下图所示:
成功生成.dll文件的话,下面没有任何提示,就是这个样子
gcc -shared -Wl,-soname,adder -o adder.dll -fPIC add.c
生成的文件会在当前目录下
3、下面是Python调用生成后的.dll文件:
下面是代码:
from ctypes import *
# load the shared object file
adder = CDLL('./adder.dll')
# 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)))