代码之家  ›  专栏  ›  技术社区  ›  Mathieu Van Nevel

马歇尔常数阵列

  •  -1
  • Mathieu Van Nevel  · 技术社区  · 6 年前

    我正试图在结构中有一个堆栈分配的数组。我是说指针。但是我希望在没有额外代码的情况下完成分配,因为我在编写代码时知道大小(我不想做大量工作) new 当我创建我的结构时)。 unsafe 这太完美了。 我试过一些东西,但效果不好。我是C#的新手,所以可能有一种方法我没有看到!

    public struct TestValue {int value; }
    
    [StructLayout(LayoutKind.Sequential)]
    public struct TestArray {
       [MarshalAs(UnmanagedType.ByValArray, SizeConst=128)] public TestValue[] s1;
    }
    
    public struct TestSpan
    {
        Span<TestValue> data= stackalloc TestValue[10];
    }
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Mathieu Van Nevel    6 年前
    using System.Runtime.InteropServices;
    
    public struct TestValue {int value; }
    
    [StructLayout(LayoutKind.Sequential)]
    public struct TestArray {
       [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=128)] public TestValue[] s1;
    }
    
    public class Foo
    {
        void test()
        {
            TestArray test = new TestArray();
            test.s1[10] = new TestValue();
        }
    }
    

    最后我只需要一点零钱!