Python ctypes返回值问题

标签 python return-value ctypes dynamic-library

为什么我有这个简单的代码

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/

相关文章:

python - Cython + ctypes?

OCaml Ctypes 和分配一个指向类型的指针

Python OpenCV 将 mat ptr 传递给 C++ 代码

python - 如何以编程方式单击 QTreeWidgetItem

python - 操作系统错误: No suitable library found for xls

python - 排序二维列表python

c++ - 我的函数不会向 C++ 中的局部变量返回值

python - Neo4j python 驱动程序连接到多个数据库

c++ - C++ 中的数组和函数

java - 如何从构造函数返回具有预设字段的新实例