c#类变量问题,不安全/固定指针赋值



好吧,我现在已经进入了一些圈子,虽然我可能会问这个问题。我有一个类,比如类a,它有一些成员变量和函数。我有一部分不安全代码,我需要将成员变量作为引用传递给它,并为该引用变量分配一些值。

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

问题是一旦函数返回,值既不存储在v1中,也不存储在v2中。那么我该如何解决这个问题呢?

谢谢!

V已经通过引用传递,所以除非您有特定的想法,否则只需将其分配给V。注意,如果这里涉及多个线程,您可能需要volatile, Interlocked或同步(如lock),这适用于对成员的所有访问(读或写)。

您可以简单地传递类变量(默认情况下是通过引用)并访问其公共字段/属性。或者你可以:

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

我无法想象一个令人信服的理由(与你给出的细节),实际上需要在内存中修复v1和v2,并获得它们的实际地址给函数。除非我误解了?

编辑:也许你的赋值语句缺少一个"*"?但是,为什么不能直接给变量赋值呢?

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