简体   繁体   English

在ac函数中返回struct

[英]Returning struct in a c function

I have something like the folowing C code: 我有类似下面的C代码:

struct MyStruct MyFunction (something here)
{
    struct MyStruct data;

    //Some code here

    return data;
}

would the returning value be a reference or a copy of the memory block for data? 返回值是数据存储块的引用还是副本? Should MyFunction return struct MyStruct* (with the corresponding memory allocation) instead of struct MyStruct? MyFunction应该返回struct MyStruct *(带有相应的内存分配)而不是struct MyStruct吗?

There is no such thing as a reference in C. So semantically speaking, you are returning a copy of the struct. 在C中没有引用这样的东西。从语义上讲,你正在返回结构的副本。 However, the compiler may optimise this. 但是,编译器可以优化它。

You cannot return the address of a local variable, as it goes out of scope when the function returns. 您不能返回局部变量的地址,因为它在函数返回时超出范围。 You could return the address of something that you've just malloc -ed, but you'll need to make it clear that someone will need to free that pointer at some point. 你可以返回你刚刚使用malloc -ed的东西的地址,但是你需要明确某个人需要在某个时刻free该指针。

It would return a copy. 它会返回一份副本。 C is a pass-by-value language. C是一种按值传递的语言。 Unless you specify that you are passing pointers around, structures get copied for assignments, return statements, and when used as function parameters. 除非您指定传递指针,否则将复制结构以进行赋值,返回语句以及用作函数参数。

It is returned as copy. 它作为副本返回。 BTW, you should not return it's reference because it has automatic storage duration ( ie, data resides on stack ). 顺便说一下,你不应该返回它的参考,因为它有自动存储持续时间(即数据驻留在堆栈上)。

I have had problems with this (a function in a DLL returning a struct) and have investigated it. 我遇到了这个问题(DLL中的一个函数返回一个结构)并对其进行了调查。 Returning a struct from a DLL to be used by people who might have a different compiler is not good practice, because of the following. 从DLL返回结构以供可能具有不同编译器的人使用是不好的做法,因为以下内容。

How this works depends on the implementation. 这是如何工作取决于实施。 Some implementations return small records in registers, but most get an invisible extra argument that points to a result struct in the local frame of the caller. 一些实现在寄存器中返回小记录,但是大多数实现获得一个不可见的额外参数,该参数指向调用者的本地帧中的结果结构。 On return, the pointer is used to copy data to the struct in the local frame of the caller. 返回时,指针用于将数据复制到调用者的本地帧中的结构。 How this pointer is passed depends on the implementation again: as last argument, as first argument or as register. 传递此指针的方式取决于实现:作为最后一个参数,作为第一个参数或寄存器。

As others said, returning references is not a good idea, as the struct you return might be in your local frame. 正如其他人所说,返回引用并不是一个好主意,因为您返回的结构可能在您的本地框架中。 I prefer functions that do not return such structs at all, but take a pointer to one and fill it up from inside the function. 我更喜欢根本不返回这些结构的函数,但是将指针指向一个并从函数内部填充它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM