Porting C++ Code to C# - Pointer Issue -


i'm trying convert c++ code c#. have functions accept pointers in c++. in c# having troubles doing it. have tried following demo code:

namespace consoleapplication1 {     class program     {         static void main(string[] args)         {             test obj = new test();             int a,b;             console.writeline("initial values");             = 20;             b = 100;             obj.setref(ref a,ref b);             console.writeline("value of a: " + a);             console.writeline("value of b: " + b);             obj.setvalref(ref a);             console.writeline("after ref");             console.writeline("value of a: " + a);             console.writeline("value of b: " + b);             console.readkey();         }        }        class test     {          public void setref(ref int x, ref int y)         {             y = x;         }          public void setvalout(out int x)         {             x = 10;          }          public void setvalref(ref int x)         {             x = 10;          }     } } 

when run output is

initial values value of a: 20 value of b: 20 after ref value of a: 10 value of b: 20 

we want if value of 1 variable changed value of second should automatically change( pointers).

the only way in c#/.net use unsafe code , declare 1 of variables pointer.

however, not advice c# code. highly consider restructuring code more c#-like or you're going fight language lot.

or, better advice, how compiling code managed c++ compiler , wrapping in nice real managed types instead of going through hassle of porting?

anyway, here's linqpad example, however, shows if must port , need ability:

void main() {     unsafe     {         int x = 10;         int* y = &x;          debug.writeline("x=" + x + ", y=" + *y);          changevalue(ref x);          debug.writeline("x=" + x + ", y=" + *y);          changevalue(ref *y);          debug.writeline("x=" + x + ", y=" + *y);     } }  static void changevalue(ref int value) {     value += 10; } 

this output:

x=10, y=10 x=20, y=20 x=30, y=30 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -