Home > Software engineering >  Change the memory address of an object in C#
Change the memory address of an object in C#

Time:03-29

Is it possible to change the memory address of an object in C# ? Example of what I want:

unsafe public Program {

public struct Foo
    {
        int a;
        int b;

    }
 static void Main(string[] args){

        Foo foo= new Foo();
        fixed(Foo *foo_ptr=&foo)   //I know I can get the object pointer here.  
        Foo foo2= new Foo();
        fixed(&foo2=foo_ptr)      //How I can do this?
}
}

I got this error when I tried the last fixed: You can only take the address of an unfixed expression inside of a fixed statement initializer csharp(CS0212)

Can someone help me? Thanks.

Edit: There is long story why I want change the memory address and not just writing that foo2=foo; . That is why I am wondering if it is possible or not? This post is not what I am asking

CodePudding user response:

Only to mark this question as answered to be useful, I pasted my comment here again.

It won't be easy to do so. Because in .Net, GC must track the address of all of the variables to de-allocate the pointer, after releasing the last anchor of the variable. Also, it's illegal because each application has it's own Application Domain and by default, no application is allowed to access to out of its boundary.

Please consider marking the question as answered. Thanks a lot.

CodePudding user response:

Suppose p is the pointer to the shared memory, you can use ref keyword to create a reference.

byte* p;
ref Foo foo = ref *(Foo*)p;
//foo.a, foo.b
  • Related