我有一个需求需要使用指针,我创建了一个Parameter类来保存这个指针。
        
public unsafe AnimatorParameter(int* value,string name)
{
    _name   = name;
    _pValue = value;
}public unsafe int GetValue()
{
    return *_pInt;
}但是我担心垃圾回收会改变原来值的地址从而导致指针失效,请问我的担心对吗?还有如果确实会失效,那么有什么办法可以避免。
unsafec#

解决方案 »

  1.   

    用关键字fixed:
      fixed (byte* p = buffer)
                {
                    if (!ReadFile(handle, p, 8192, &n, 0))
                    {
                        return 0;
                    }
                }
      

  2.   

    你使用了fixed,但这个指针的生命周期应该仅在fixed语句块内。如果我想要一直保留一个指针,生命周期和程序运行时间一样长改怎么做?