1

我是 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

4

1 回答 1

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

于 2013-06-28T07:39:31.500 回答