1. 程式人生 > >Python呼叫C語言

Python呼叫C語言

Python中的ctypes模組可能是Python呼叫C方法中最簡單的一種。ctypes模組提供了和C語言相容的資料型別和函式來載入dll檔案,因此在呼叫時不需對原始檔做任何的修改。也正是如此奠定了這種方法的簡單性。

示例如下

實現兩數求和的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

在這個例子中,C檔案是自解釋的,它包含兩個函式,分別實現了整形求和和浮點型求和。

在Python檔案中,一開始先匯入ctypes模組,然後使用CDLL函式來載入我們建立的庫檔案。這樣我們就可以通過變數adder來使用C類庫中的函數了。當adder.add_int()被呼叫時,內部將發起一個對C函式add_int的呼叫。ctypes介面允許我們在呼叫C函式時使用原生Python中預設的字串型和整型。

而對於其他類似布林型和浮點型這樣的型別,必須要使用正確的ctype型別才可以。如向adder.add_float()

函式傳參時, 我們要先將Python中的十進位制值轉化為c_float型別,然後才能傳送給C函式。這種方法雖然簡單,清晰,但是卻很受限。例如,並不能在C中對物件進行操作。