为什么我有这个简单的代码
void voidFunct() {
printf("voidFunct called!!!\n");
}
我把它编译成一个动态库
gcc -c LSB.c -o LSB.o
gcc -shared -Wl -o libLSB.so.1 LSB.o
然后我使用 ctypes 从 python 解释器调用函数
>>> from ctypes import *
>>> dll = CDLL("./libLSB.so.1")
>>> return = dll.voidFunct()
voidFunct called!!!
>>> print return
17
为什么从 void
方法返回的值是 17
而不是 None
或类似的?谢谢。
最佳答案
来自文档:
class ctypes.CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)Instances of this class represent loaded shared libraries. Functions in these libraries use the standard C calling convention, and are assumed to return int.
简而言之,您将 voidFunct() 定义为返回 int
的函数,而不是 void,并且 Python 期望它返回 int
(无论如何,它会以某种方式返回- 它恰好是一个随机值)。
您可能应该做的是显式声明返回值类型为 None
。
dll.voidFunct.restype = None
关于Python ctypes返回值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6073599/