這期內容當中小編將會給大家帶來有關怎么在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語言了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。