开发者

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 开发者_Python百科soon as the function returns, the values are not stored in either v1 or v2. So how do I fix this?

Thanks!


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).


You could simply pass the class variable (which would be by reference by default) and access its public fields/properties. Or you could:

Method(ref myA.v1);

public unsafe void Method(ref int 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.
 }

I can't imagine a compelling reason (with the details you gave) to actually need to fix v1 and v2 in memory and get their actually addresses to give to the function. Unless I've misunderstood?

EDIT: Perhaps your assignment statements are missing a '*'? But again, why can't you just assign to the variables directly?

fixed (int *p2 = p1)
{
       // Assign values.
       *p2 = 42;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜