使用 ctypes 从 python 调用 C 函数

Mar*_*Mim 5 c python ctypes call wrapper

我有以下 C 代码。我正在尝试使用以下命令从 Python 调用此函数ctypes

int add ( int arr []) 
{
    printf("number %d \n",arr[0]);
    arr[0]=1;
    return arr[0];
}
Run Code Online (Sandbox Code Playgroud)

我用以下方法编译了这个:

gcc -fpic -c test.c 
gcc -shared -o test.so test.o
Run Code Online (Sandbox Code Playgroud)

然后把它放进去/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
Run Code Online (Sandbox Code Playgroud)

但我总是得到一些大数字,比如-1365200.

我也尝试过:

dll.add.argtypes=POINTER(c_type_int)
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

Syl*_*oux 2

尝试围绕它构建:

\n\n
lib = 'test.so'\ndll = cdll.LoadLibrary(lib)\n\ndll.add.argtypes=[POINTER(c_int)]\n#                ^^^^^^^^^^^^^^^^\n#         One argument of type `int *\xcc\x80\n\ndll.add.restype=c_int\n# return type \n\nres =dll.add((c_int*5)(5,1,7,33,99))\n#            ^^^^^^^^^\n#       cast to an array of 5 int\n\nprint res\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用 Python 2.7.3 和 2.6.9 进行测试

\n