Reputation: 493
I was wondering is it safe to return a fixed pointer from one method to another method - does the pinned object still stay fixed? e.g.
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. But since I changed it to e.g. set value direct from Class1 i haven't seen the issue occur.
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". .. i get it now though it's speaking about my var "ptr" in "Test()" already being fixed..
Upvotes: 4
Views: 4425
Reputation: 726669
Returning from the method ends the scope of fixed
, hence the pointer is no longer fixed once you return. It is safe to pass fixed pointers up the chain, e.g.
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.
Upvotes: 11