Marshal size const array

601 Views Asked by At

I'm trying to have a stack allocated array inside a struct. Well the pointer I mean. But I'd like the allocation to be done without extra code because I know the size when I write the code (I don't want to do a bunch of new when I create my struct). If I can even do it without unsafe context that's perfect. I tried some stuff, but it's not doing fine. I'm brand new to C# so there is probably a way to do it that I didn't see !

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

There are 1 best solutions below

1
On BEST ANSWER
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();
    }
}

I needed just a small change in the end!