此行为在 C# 中是否有效
public class MyClass
{
private byte[] data;
public MyClass()
{
this.data = new byte[1024];
}
public unsafe byte* getData()
{
byte* result = null;
fixed (byte* dataPtr = data)
{
result = dataPtr;
}
return result;
}
}
最佳答案
如果您要关闭安全系统,则您有责任确保程序的内存安全。一旦您这样做,您必须在没有安全系统帮助您的情况下安全地完成所有操作。这就是“不安全”的意思。
正如 C# 规范明确指出的那样:
the address of a moveable variable can only be obtained using a fixed statement, and that address remains valid only for the duration of that fixed statement.
您正在获取可移动变量的地址,然后在固定语句的持续时间后使用它,因此该地址不再有效。因此,您被特别要求不要做您正在做的事。
在您对必须遵守的规则有透彻而深刻的理解之前,您不应编写任何不安全的代码。从阅读规范的第 18 章开始。
关于c# - 获取指向字节数组的指针的不安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10076262/