python - 使用ctypes从python调用C函数

标签 python c call wrapper 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)

但它不起作用。

最佳答案

相反,尝试:

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

关于python - 使用ctypes从python调用C函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25407258/

相关文章:

c - 如何防止Waf重命​​名目标文件?

python - IPython 代码从 Python 2 迁移到 Python 3

python - 过滤掉 Pandas DataFrame 中的 "empty array"值

python - 在 Python 中将轴作为 **kwarg 传递

c - 确定给定用户内存大小和偏移量的所有可能的 32KB block 数

java:获取 sqlexception 消息 "incorrrect syntax near ' {' "

python - 通过求和执行分组后保留多索引列结构

c - 我已经安装了 SDL,但它似乎仍然无法正常工作

iphone - 从 iphone 的不同 View Controller 调用函数

python - 如何在 Python 中调用 AutoIt 脚本