Search code examples
c#fixedunsafe

C# Problem with class variable, unsafe/fixed pointer assignment


Ok, I have been into some circles now and though I might ask this at SO. I have a class lets say Class A with some member variables and functions. I have a portion of unsafe code to which I need to pass the member variable as a reference and assign some values to that reference variable.

Class A
{
   int v1;
   int v2;
....

 public unsafe void Method(ref V)
 {
    // Here I need to have something like a 
    // pointer that will hold the address of V (V will be either v1 or v2)            
    // Assign some values to V till function returns.
     int *p1 = &V
      fixed (int *p2 = p1)
      {
       // Assign values.
       }
 }
}

The problem is as soon as the function returns, the values are not stored in either v1 or v2. So how do I fix this?

Thanks!


Solution

  • V is already pass-by-reference, so unless you have something specific in mind: just assign to V. Note that if multiple threads are involved here you might need volatile, Interlocked or synchronisation such as lock - and this applies to all access to the member (read or write).