在回答自己的有争议的问题时,Mash阐述了您不需要使用"unsafe"关键字就能直接读写任何.NET对象实例的字节。您可以声明以下类型:
[StructLayout(LayoutKind.Explicit)]
struct MemoryAccess
{
[FieldOffset(0)]
public object Object;
[FieldOffset(0)]
public TopBytes Bytes;
}
class TopBytes
{
public byte b0;
public byte b1;
public byte b2;
public byte b3;
public byte b4;
public byte b5;
public byte b6;
public byte b7;
public byte b8;
public byte b9;
public byte b10;
public byte b11;
public byte b12;
public byte b13;
public byte b14;
public byte b15;
}
然后你可以做一些像改变"immutable"字符串的事情。以下代码在我的机器上打印出"bar":
string foo = "foo";
MemoryAccess mem = new MemoryAccess();
mem.Object = foo;
mem.Bytes.b8 = (byte)'b';
mem.Bytes.b10 = (byte)'a';
mem.Bytes.b12 = (byte)'r';
Console.WriteLine(foo);
您还可以使用相同的技术破坏对象引用来触发AccessViolationException异常。
问题:我认为(在纯托管的C#代码中)需要使用unsafe关键字才能完成此类操作。为什么这里不需要?这是否意味着纯托管的“安全”代码实际上并不安全?