Python ctypes返回值问题

2024-04-19 11:08:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有这个简单的代码

void voidFunct() {
      printf("voidFunct called!!!\n");
}

我把它编译成一个动态库

gcc -c LSB.c -o LSB.o 
gcc -shared -Wl -o libLSB.so.1 LSB.o 

我从python解释器调用函数,使用ctypes

>>> from ctypes import *
>>> dll = CDLL("./libLSB.so.1")
>>> return = dll.voidFunct()
voidFunct called!!!
>>> print return
17

为什么从void方法返回的值是17,而不是None或类似的值?谢谢您。


Tags: 代码return动态ctypessharedgccdll编译成
2条回答

那是不确定的行为。您要求ctypes读取一个根本不存在的返回值。它从堆栈中读取一些内容,但返回的内容定义不清。

从文档中:

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

相关问题 更多 >