Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass c# struct by reference?

Tags:

c#

In my c# application i receive pointer to c++ struct in callback/delegate. 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.

Now I want to pass reference to struct for further processing

  • I can't use class because it probably will not "map" perfectly to c++ struct.
  • I don't want to copy struct for better latency

How can I do that?


This example demonstrates that struct is passed by value, not by reference:

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 
like image 817
Oleg Vazhnev Avatar asked May 17 '13 17:05

Oleg Vazhnev


People also ask

What is pass in C?

Calling a C function (aka invoke a function)The args are a list of values (or variables containing values) that are "passed" into the function. The number of args "passed" into a function must exactly match the number of parameters required for the function.

Does C++ have pass?

In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables.

What's pass in Python?

Python pass Statement The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops, function definitions, class definitions, or in if statements.


1 Answers

It sounds like you just want to use ref to pass the struct by reference:

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.

Note that other than for interop, I would normally strongly recommend against using mutable structs like this. I can understand the benefits here though.

like image 186
Jon Skeet Avatar answered Sep 21 '22 00:09

Jon Skeet