[英]Calling C function from python using ctypes
我有以下C代碼。 我正在嘗試使用ctypes
從Python調用此函數:
int add ( int arr [])
{
printf("number %d \n",arr[0]);
arr[0]=1;
return arr[0];
}
我使用以下命令編譯了此文件:
gcc -fpic -c test.c
gcc -shared -o test.so test.o
然后將其放在/usr/local/lib
。
Python對此的調用是:
from ctypes import *
lib = 'test.so'
dll = cdll.LoadLibrary(lib)
IntArray5 = c_int * 5
ia = IntArray5(5, 1, 7, 33, 99)
res = dll.add(ia)
print res
但是我總是得到一些大的數字,如-1365200
。
我也嘗試過:
dll.add.argtypes=POINTER(c_type_int)
但它不起作用。
嘗試圍繞它構建:
lib = 'test.so'
dll = cdll.LoadLibrary(lib)
dll.add.argtypes=[POINTER(c_int)]
# ^^^^^^^^^^^^^^^^
# One argument of type `int *̀
dll.add.restype=c_int
# return type
res =dll.add((c_int*5)(5,1,7,33,99))
# ^^^^^^^^^
# cast to an array of 5 int
print res
使用Python 2.7.3和2.6.9進行了測試
相反,請嘗試:
dll = cdll.LoadLibrary('test.so')
res = dll.add(pointer(c_int(5)))
print res
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.