在 C# 中返回固定指针
我想知道从一种方法返回固定指针到另一种方法是否安全 - 固定对象是否仍然保持固定?例如,
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;
}
}
我问的原因是使用这种风格的东西,我一直收到 AccessViolation 异常。但自从我将其更改为例如直接从 Class1 设置值以来,我还没有看到问题发生。
编辑: 我认为它可能被修复的原因是,如果从“TestData * ptr = x.GetDataPtr()”之外尝试放置fixed(),你会得到“你无法获取已经固定的表达式的地址”。 ..我现在明白了,虽然它说的是我的“Test()”中的 var“ptr”已经被修复了。
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..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从方法返回结束了固定的范围,因此一旦返回,指针就不再固定。在链上传递固定指针是安全的,例如
,但返回会使指针再次变得非固定。
从逻辑上讲,这是有道理的:CLR 没有其他方法可以决定指针从调用返回后何时应变为非固定。
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.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.