我正在寻找一种方法来将任意不安全的内存区域重新解释为 C# 中的 blittable 结构。到目前为止,这是我可以写的一次失败的尝试:
[StructLayout(LayoutKind.Explicit, Size = sizeof(int))]
struct Foo
{
[FieldOffset(0)]
public int X;
}
public static unsafe void Main()
{
// Allocate the buffer
byte* buffer = stackalloc byte[sizeof(Foo)];
// A tentative of reinterpreting the buffer as the struct
Foo foo1 = Unsafe.AsRef<Foo>(buffer);
// Another tentative to reinterpret as the struct
Foo foo2 = *(Foo*) buffer;
// Get back the address of the struct
void* p1 = &foo1;
void* p2 = &foo2;
Console.WriteLine(new IntPtr(buffer).ToString("X"));
Console.WriteLine(new IntPtr(p1).ToString("X"));
Console.WriteLine(new IntPtr(p2).ToString("X"));
}
尽管如此,打印的内存地址都是不同的(我希望打印相同的地址)。第一次尝试使用Unsafe.AsRef<T>(..)
微软提供的方法,其中方法的描述说:
将给定位置重新解释为对 type 值的引用
T
。
我不确定为什么这里没有正确完成重新解释。
有什么建议吗?