在 C# 中使用转换指针值的引用 return 可以吗?

Is it ok to use a reference return of the converted pointer's value in C#?

可以使用转换指针值的引用 return 吗?

这个问题我看过了。

关于垃圾收集器的内存移动问题,可以使用下面的代码吗? (Helper.GetReference() & Helper.GetPointer())

class Program
{
    static unsafe void Main(string[] args)
    {
        byte[] bytes = new byte[1024];

        ref SomeStruct reference = ref Helper.GetReference<SomeStruct>(bytes);
        reference.field1 = 1;
        reference.field2 = 2;

        SomeStruct* pointer = Helper.GetPointer<SomeStruct>(bytes);
        pointer->field1 = 3;
        pointer->field2 = 4;
    }
}

public static class Helper
{
    // Can I use this?
    public static unsafe ref T GetReference<T>(byte[] bytes) where T : unmanaged
    {
        fixed (byte* p1 = bytes)
        {
            T* p2 = (T*)p1;
            return ref *p2;
        }
    }

    // Shouldn't I use it?
    public static unsafe T* GetPointer<T>(byte[] bytes) where T : unmanaged
    {
        fixed (byte* p1 = bytes)
        {
            return (T*)p1;
        }
    }
}

public struct SomeStruct
{
    public int field1;
    public int field2;
}

据我所知,这两种方法都是 不安全...是的,它确实可以编译,但是,因为您在 [=12] 中使用了 unsafe =] 方法并引用相同的内存,您的 safety-net 已被破坏。

指向 可以由垃圾收集器(又名您的数组)移动的内存部分(托管对象) ), 可能会给你留下一个 悬空指针

您需要 修复 (fixed) 您的 Main 方法中的数组以确保安全(我是这样看的),或者您的结构

例如

fixed (byte* p = bytes) // even though p isn't being used
{
   SomeStruct* pointer = Helper.GetPointer<SomeStruct>(bytes);
   pointer->field1 = 3;
   pointer->field2 = 4;
}