简体   繁体   English

在C#中返回一个固定的指针

[英]Return a fixed pointer in C#

I was wondering is it safe to return a fixed pointer from one method to another method - does the pinned object still stay fixed? 我想知道将固定指针从一个方法返回到另一个方法是否安全 - 固定对象是否仍然保持固定? eg 例如

struct TestData
{
    public int value;
}

public class Class1
{
    private TestData data; 

    public unsafe TestData* GetDataPtr()
    {
        fixed (TestData* ptr = &data)
        {
            // IS THIS SAFE?
            return ptr; 
        }
    }
}

public class Class2
{
    public unsafe void Test()
    {
        Class1 x = new Class1();

        TestData* ptr = x.GetDataPtr(); // is this still fixed?
        ptr->value = 2; 
    }
}

The reason i'm asking is using something in this style I've been getting AccessViolation exceptions. 我问的原因是使用这种风格的东西我一直在获得AccessViolation异常。 But since I changed it to eg set value direct from Class1 i haven't seen the issue occur. 但是因为我将它改为例如直接从Class1设定值我没有看到问题发生。

EDIT: the reason i thought it may be fixed is if from outside the "TestData* ptr = x.GetDataPtr()" you try to put fixed( ) you get "you cannot take the address of an already fixed expression". 编辑:我认为可能修复的原因是,如果从“TestData * ptr = x.GetDataPtr()”之外你试图将fixed()置于“你不能获取已经修复的表达式的地址”。 .. i get it now though it's speaking about my var "ptr" in "Test()" already being fixed.. ..我现在得到它虽然它正在谈论我在“Test()”中的var“ptr”已经被修复了..

Returning from the method ends the scope of fixed , hence the pointer is no longer fixed once you return. 从方法返回结束fixed的范围,因此一旦返回指针就不再固定。 It is safe to pass fixed pointers up the chain, eg 将固定指针传递到链上是安全的,例如

fixed(TestData* ptr = &data) {
    MyFunction1(ptr);
    MyFunction2(ptr);
}

But returning makes the pointer non-fixed again. 但是返回使得指针再次不固定。

Logically, this makes sense: there is no alternative way for the CLR to decide when the pointer should become non-fixed after you have returned it from the call. 从逻辑上讲,这是有道理的:在您从调用返回指针后,CLR无法决定何时指针应该变为非固定状态。

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

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