[英]Calling C function from python using ctypes
I have the following C code. 我有以下C代码。 I am trying to call this function from Python using
ctypes
: 我正在尝试使用
ctypes
从Python调用此函数:
int add ( int arr [])
{
printf("number %d \n",arr[0]);
arr[0]=1;
return arr[0];
}
I compiled this by using: 我使用以下命令编译了此文件:
gcc -fpic -c test.c
gcc -shared -o test.so test.o
then put it in /usr/local/lib
. 然后将其放在
/usr/local/lib
。
Python call for this was: 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
but I always get some big number like -1365200
. 但是我总是得到一些大的数字,如
-1365200
。
I tried also: 我也尝试过:
dll.add.argtypes=POINTER(c_type_int)
but it does not work. 但它不起作用。
Try to build around that: 尝试围绕它构建:
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
Tested both with Python 2.7.3 and 2.6.9 使用Python 2.7.3和2.6.9进行了测试
Instead, try: 相反,请尝试:
dll = cdll.LoadLibrary('test.so')
res = dll.add(pointer(c_int(5)))
print res
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.