将 C# 原始缓冲区重新解释为 blittable 结构

Reinterpret C# raw buffer into a blittable structure

我正在寻找一种方法来将任意不安全内存区域重新解释为 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>(..),方法描述中说:

Reinterprets the given location as a reference to a value of type T.

我不确定为什么这里没有正确地重新解释。

有什么建议吗?

重新解释按预期进行,地址不同的原因是这两行在两个新变量中创建了独立的数据副本:

Foo foo1 = Unsafe.AsRef<Foo>(buffer);
// ...
Foo foo2 = *(Foo*) buffer;

为避免复制,您可以将变量声明为 ref 局部变量(从 C#7 开始)或指针:

byte* buffer = ...

// Option 1, pointers only
Foo* foo1 = (Foo*)buffer;
foo1->X = 123;

// Option 2, ref local cast from pointer    
ref Foo foo2 = ref *(Foo*)buffer;
foo2.X = 456;

// Option 3, ref local with Unsafe.AsRef
// Unlike option 2 this also allows reinterpreting non-blittable types,
// but in most cases that's probably undesirable
ref Foo foo3 = ref Unsafe.AsRef<Foo>(buffer);
foo3.X = 789;