C 如何返回一个结构体? [英] How does C return a structure?

查看:87
本文介绍了C 如何返回一个结构体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(gdb) disas func
Dump of assembler code for function func:
0x00000000004004b8 <func+0>:    push   %rbp
0x00000000004004b9 <func+1>:    mov    %rsp,%rbp
0x00000000004004bc <func+4>:    movl   $0x64,0xfffffffffffffff0(%rbp)
0x00000000004004c3 <func+11>:   movb   $0x61,0xfffffffffffffff4(%rbp)
0x00000000004004c7 <func+15>:   mov    0xfffffffffffffff0(%rbp),%rax
0x00000000004004cb <func+19>:   leaveq
0x00000000004004cc <func+20>:   retq
End of assembler dump.


t_test func()
{
    t_test t;
    t.i = 100;
    t.c = 'a';
    return t;
}

所以看起来它返回的是局部变量t,但是这种工作保证可以工作,不是应该在返回时不引用任何局部变量吗??

So it seems it's returning the local variable t,but is this kind of job guaranteed to work, isn't it supposed not to refer to any local variables when return??

推荐答案

根据我的经验,C 返回结构的方式没有标准方法.为了能够传递结构体,编译器通常(对用户不可见)传递一个指向结构体的指针,函数可以将内容复制到该结构体.这个指针是如何传递的(栈上的第一个或最后一个)是依赖于实现的.一些编译器,如 32 位 MSVC++,在 EAX 和 EDX 等寄存器中返回小结构.显然,GCC 在 RAX 中以 64 位模式返回这样一个结构体.

In my experience, there is no standard way how C returns a structure. To be able to pass a struct, the compiler usually (invisibly to the user) passes a pointer to the struct, to which the function can copy the contents. How this pointer is passed (first or last on stack) is implementation dependent. Some compilers, like 32 bit MSVC++ return small structures in registers like EAX and EDX. Apparently, GCC returns such a struct in RAX, in 64 bit mode.

但是,再一次,没有标准的方法来做到这一点.当使用函数的其余代码也由同一个编译器编译时,这没有问题,但如果函数是 DLL 或 lib 的导出函数,则有问题.当使用来自不同语言 (Delphi) 或来自不同编译器的 C 的此类函数时,我已经被这个问题咬了几次.请参阅此链接 也是.

But, once again, there is no standard way how this is done. That is no problem when the rest of the code using a function is also compiled by the same compiler, but it is a problem if the function is an exported function of a DLL or a lib. I have been bitten by this a few times, when using such functions from a different language (Delphi) or from C with a different compiler. See this link too.

这篇关于C 如何返回一个结构体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆