小编Mar*_*Mim的帖子

使用 ctypes 从 python 调用 C 函数

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

但它不起作用。

c python ctypes call wrapper

5
推荐指数
1
解决办法
7106
查看次数

标签 统计

c ×1

call ×1

ctypes ×1

python ×1

wrapper ×1