简体   繁体   English

通过引用传递c#struct?

[英]pass c# struct by reference?

In my c# application i receive pointer to c++ struct in callback/delegate. 在我的c#应用程序中,我在callback / delegate中收到指向c ++ struct的指针。 I'm not sure if class can do the trick but just casting c++ pointer to appropriate c# struct works fine, so I'm using c# struct for storing data. 我不确定class可以做到这一点,但只是将c ++指针转换为适当的c#struct工作正常,所以我使用c#struct来存储数据。

Now I want to pass reference to struct for further processing 现在我想传递对struct的引用以进行进一步处理

  • I can't use class because it probably will not "map" perfectly to c++ struct. 我不能使用class因为它可能不会完美地“映射”到c ++ struct。
  • I don't want to copy struct for better latency 我不想复制struct以获得更好的延迟

How can I do that? 我怎样才能做到这一点?


This example demonstrates that struct is passed by value, not by reference: 此示例演示struct是按值传递的,而不是通过引用传递的:

using System;

namespace TestStruct
{
    struct s
    {
        public int a;
    }

    class Program
    {
        static void Main(string[] args)
        {
            s s1 = new s
                       {
                           a = 1
                       };
            Foo(s1);
            Console.WriteLine("outer a = " + s1.a);
        }

        private static void Foo(s s1)
        {
            s1.a++;
            Console.WriteLine("inner a = " + s1.a);
        }

    }
}

Output is: 输出是:

inner a = 2
outer a = 1

It sounds like you just want to use ref to pass the struct by reference: 听起来你只想使用ref通过引用传递结构:

private static void Foo(ref s s1)
{
    s1.a++;
    Console.WriteLine("inner a = " + s1.a);
}

And at the call site: 在通话现场:

Foo(ref s1);

See my article on parameter passing in C# for more details. 有关更多详细信息,请参阅我在C#中传递参数的文章

Note that other than for interop, I would normally strongly recommend against using mutable structs like this. 请注意,除了互操作之外,我通常强烈建议不要使用像这样的可变结构。 I can understand the benefits here though. 我可以理解这里的好处。

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

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