简体   繁体   English

C#类变量问题,不安全/固定的指针分配

[英]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. 好的,虽然现在我可能会在SO上问这个问题,但是我已经进入了一些圈子。 I have a class lets say Class A with some member variables and functions. 我有一个类,可以说类A具有一些成员变量和函数。 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. 问题是函数返回后,值不会立即存储在v1或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 . V已经是传递引用,所以除非您有特定的想法:只需将其分配给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). 请注意,如果此处涉及多个线程,则可能需要volatileInterlocked或同步(例如lock ),这适用于对该成员的所有访问(读或写)。

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. 我无法想象有一个令人信服的理由(使用您提供的详细信息)实际上需要修复内存中的v1和v2并获取它们的实际地址以提供给该函数。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM