当声明为函数的返回值时,是否将C#结构装箱? [英] Is a C# struct ever boxed when declared as the return value of a function?

查看:66
本文介绍了当声明为函数的返回值时,是否将C#结构装箱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,但是我没有在Stack Overflow上找到明确的答案.

A simple question, but I haven't found a definitive answer on Stack Overflow.

    struct MyStruct { int x, y, z; }

    MyStruct GetMyStruct() => new MyStruct();

    static void Main()
    {
        var x = GetMyStruct();      // can boxing/unboxing ever occur?
    }

从函数返回时,是否总是将 C#结构(值类型) 复制到堆栈中,无论它有多大?我不确定的原因是,对于MSIL以外的某些指令集(例如x86),通常需要将返回值放入处理器寄存器中,并且堆栈不直接涉及.

Is a C# struct (value type) always copied to the stack when returned from a function, no matter how large it might be? The reason I'm unsure is that for some instruction sets other than MSIL (such as x86), a return value usually needs to fit into a processor register, and the stack is not directly involved.

如果是,是调用站点为<预期>值返回类型在 CLR 堆栈上预分配了空间吗?

If so, is it the call site that pre-allocates space on the CLR stack for the (expected) value return type?

对于原始问题,答案是否定的. CLR 绝不会(无声地)装箱一个结构,只是为了将其作为返回值发送.

[edit: summary of replies:] For the intent of the original question, the answer is no; the CLR will never (silently) box a struct just for the purpose of sending it as a return value.

推荐答案

这是JIT编译器的详尽实现细节.通常,如果结构足够小且具有简单成员,则其将返回到CPU寄存器中.如果太大,则调用代码将在堆栈上保留足够的空间,并将指针作为额外的隐藏参数传递给该空间.

It is a heavy implementation detail of the JIT compiler. In general, if the struct is small enough and has simple members then its gets returned in CPU registers. If it gets too big then the calling code reserves enough space on the stack and passes a pointer to that space as an extra hidden argument.

它永远不会装箱,除非方法的返回类型当然是 object .

It will never be boxed, unless the return type of the method is object of course.

前进:这也是调试器无法在自动"窗口中显示该函数的返回值的原因.有时会很痛苦.但是调试器无法从JIT编译器中获取足够的元数据,无法确切知道在哪里可以找到该值.已在VS2013中修复.

Fwiw: this is also the reason that the debugger cannot display the return value of the function in the Autos window. Painful sometimes. But the debugger doesn't get enough metadata from the JIT compiler to know exactly where to find the value. fixed in VS2013.

这篇关于当声明为函数的返回值时,是否将C#结构装箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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