使用ctypes从Python调用C函数

5

我有如下的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)

但它无法正常工作。

2个回答

4

相反,尝试:

dll = cdll.LoadLibrary('test.so')
res = dll.add(pointer(c_int(5)))
print res

2

尝试围绕这个构建:

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上进行了测试


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接