这期内容当中小编将会给大家带来有关怎么在Python项目中调用C语言,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
示例如下
实现两数求和的C代码,保存为add.c
//sample C file to add 2 numbers - int and floats
#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;
}
接下来将C文件编译为.so文件(windows下为DLL)。下面操作会生成adder.so文件
#For Linux
$ gcc -shared -Wl,-soname,adder -o adder.so -fPIC add.c
#For Mac
$ gcc -shared -Wl,-install_name,adder.so -o adder.so -fPIC add.c
#For windows
$
gcc -shared -Wl,-soname,adder -o adder.dll -fPIC add.c
现在在你的Python代码中来调用它
from ctypes import *
#load the shared object file
adder = CDLL('./adder.so')
#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))
输出如下
Sum of 4 and 5 = 9
Sum of 5.5 and 4.1 = 9.60000038147
上述就是小编为大家分享的怎么在Python项目中调用C语言了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注天达云行业资讯频道。