gpt4 book ai didi

C:通过堆栈/寄存器问题返回值

转载 作者:太空狗 更新时间:2023-10-29 16:33:52 24 4
gpt4 key购买 nike

我是C新手,有一件事我不明白。当函数返回不大于寄存器的值时——我的编译器将它放在 EAX 中。当我返回大结构(不是指针而是结构本身)时——它是通过堆栈返回的。

我的问题是:编译器如何知道如何调用另一个对象导出的函数?有一个调用约定(如 stdcall),但它是关于传递参数,而不是读取返回值,对吧?

应该有一些规则,例如“如果声明的返回值大于 EAX,则从 [bp-...] 中获取它”。

还有一个:如果我想返回的对象大于寄存器,应该存储在堆中并通过指针返回以防止堆栈操作,这样说是否正确?

谢谢。

最佳答案

将返回值传递给调用者的方式也是函数调用约定的一部分。参见 here .

例如,关于cdecl:

The cdecl calling convention is used by many C systems for the x86 architecture. In cdecl, function parameters are pushed on the stack in a right-to-left order. Function return values are returned in the EAX register (except for floating point values, which are returned in the x87 register ST0).

[...]

There are some variations in the interpretation of cdecl, particularly in how to return values. As a result, x86 programs compiled for different operating system platforms and/or by different compilers can be incompatible, even if they both use the cdecl convention and do not call out to the underlying environment. Some compilers return simple data structures with the length of 2 registers or less in EAX:EDX, and larger structures and class objects requiring special treatment by the exception handler (e.g., a defined constructor, destructor, or assignment) are returned in memory. To pass "in memory", the caller allocates memory and passes a pointer to it as a hidden first parameter; the callee populates the memory and returns the pointer, popping the hidden pointer when returning.

如果在堆上分配内存,则堆栈操作将比所需的堆操作快得多,因此堆栈总是更快。 (在 C 语言中)您可能想要返回指向堆上某物的指针的唯一原因是它不适合堆栈。

澄清:

在上面的最后一句话中,“你可能想要的唯一原因……”不应被解释为“通常没有理由返回指针”。相反,我的意思是“如果您可以在不返回指针的情况下做您需要的事情,那么无论如何决定使用指针的唯一原因是......”。

当然,正如 Chris 在他自己的回答中所述,从函数返回指针有很多正当理由,但我只是在谈论您不需要这样做的情况。

换句话说,尽可能按值(value)返回;必要时使用指针

关于C:通过堆栈/寄存器问题返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5366121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com