使用ctypes从Python调用C函数

6 投票
2 回答
7200 浏览
提问于 2025-04-18 17:55

我有一段C语言代码。我想通过Python来调用这个函数,使用的是ctypes这个库:

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 个回答

5

相反,可以试试:

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

撰写回答