Python ctypes返回值问题
为什么如果我有这个简单的代码,
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
或类似的?谢谢。
Why if i have this simple code
void voidFunct() {
printf("voidFunct called!!!\n");
}
I compile it as a dynamic library with
gcc -c LSB.c -o LSB.o
gcc -shared -Wl -o libLSB.so.1 LSB.o
And i call function from a python interpreter, using ctypes
>>> from ctypes import *
>>> dll = CDLL("./libLSB.so.1")
>>> return = dll.voidFunct()
voidFunct called!!!
>>> print return
17
why the value returned from a void
method is 17
and not None
or similar? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自文档:
简而言之,您将 voidFunct() 定义为返回 int 的函数,而不是 void,并且 Python 期望它返回一个 int (无论如何,它都会得到它 - 它只是恰好是一个随机值)。
您可能应该做的是显式声明返回值类型
None
。From the docs:
In short, you defined voidFunct() as a functioning returning
int
, not void, and Python expects it to return anint
(which it gets, somehow, anyway - it's just happen to be a random value).What you should probably do, is to explicitly state a return value type of
None
.这是未定义的行为。您要求 ctypes 读取根本不存在的返回值。它从堆栈中读取一些内容,但返回的内容是不明确的。
That's undefined behaviour. You are asking ctypes to read a return value that is simply not there. It reads something off the stack, but what comes back is ill-defined.
基于上面 Boaz Yaniv 的答案:
===QUOTE===
简而言之,您将
voidFunct()
定义为返回int
的函数,而不是void< /code>,Python 希望它返回一个
int
。...
您可能应该做的是显式声明
None
的返回值类型:===UNQUOTE===
如果研究 C 的内部结构,整数返回值将返回到调用者通过 ax/eax 寄存器,而不是通过堆栈或类似的方式。因此打印出来的值并不完全是随机的,而是函数返回时恰好位于 ax 寄存器中的值。
在这种情况下,最近使用的 ax/eax 寄存器是 printf() 语句的(未使用的)返回值 - 这是 printf() 函数写入控制台的字节数。
(请注意,字符串“voidFunct called!!!\n”的长度是 20,而不是 17。我们可以相当肯定,上面提到的 C 程序并不完全是逐字运行的)
Building on the answer from Boaz Yaniv above:
===QUOTE===
In short, you defined
voidFunct()
as a function returningint
, notvoid
, and Python expects it to return anint
....
What you should probably do, is to explicitly state a return value type of
None
:===UNQUOTE===
If one looks into the internals of C, integer return values are returned to the caller via the ax/eax register, rather than via the stack or similar. So the value being printed out is not exactly random, but the value that happens to be in the ax register when the function returned.
In this case, the most recent use of the ax/eax register was the (unused) return value from the printf() statement - which is the number of bytes written to the console by the printf() function.
(Note that the length of the string "voidFunct called!!!\n" is 20, not 17. We can be fairly sure that C program mentioned above is not exactly verbatim of what was run)