我是python的新手,我正在尝试从python调用C函数并希望接收两个变量。为了简单起见,我展示了我的示例代码:
#include <Python.h>
#include <stdio.h>
PyObject* foo(char *p)
{
printf("%s\n", p);
return Py_BuildValue("ii", 2, 2);
}
>>> from ctypes import cdll
>>> lib = cdll.LoadLibrary('./lib1.so')
>>> d = lib.foo('hello')
hello
>>> d
43128392
为什么打印不正确值?
编译命令: gcc -c -IC:\ Python26 \ include 1.c -o 1.o
gcc -shared -Wl,-soname,lib1.so -o lib1.so 1.o -LC:\ Python26 \ libs -LC:\ Python26 \ PCbuild -lpython26
答案 0 :(得分:2)
默认情况下,ctypes
期望函数返回int
,并且您将返回一个对象。您需要更改函数的返回值:
from ctypes import cdll, py_object
lib = cdll.LoadLibrary('./lib1.so')
d = lib.foo('hello')
print d # prints address of object
lib.foo.restype = py_object # change the result type
d = lib.foo('hello')
print d # prints (2, 2) as expected
您可以在此处找到更多信息:http://docs.python.org/2/library/ctypes.html#return-types