C# 封送处理大小常量数组

C# 封送处理大小常量数组,c#,marshalling,stack-allocation,C#,Marshalling,Stack Allocation,我正试图在结构中有一个堆栈分配的数组。我是说指针。但是我希望在没有额外代码的情况下完成分配,因为我在编写代码时知道大小(我不想在创建结构时做大量的new)。 如果我甚至可以在没有不安全的上下文的情况下完成它,那就太完美了。 我试过一些东西,但效果不好。我是C#的新手,所以可能有一种方法我没有看到 public struct TestValue {int value; } [StructLayout(LayoutKind.Sequential)] public struct TestArray

我正试图在结构中有一个堆栈分配的数组。我是说指针。但是我希望在没有额外代码的情况下完成分配,因为我在编写代码时知道大小(我不想在创建结构时做大量的
new
)。 如果我甚至可以在没有
不安全的
上下文的情况下完成它,那就太完美了。
我试过一些东西,但效果不好。我是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];
}
public struct TestValue{int value;}
[StructLayout(LayoutKind.Sequential)]
公共结构测试阵列{
[Marshallas(UnmanagedType.ByValArray,SizeConst=128)]公共测试值[]s1;
}
公共结构TestSpan
{
跨度数据=stackalloc测试值[10];
}

最后我只需要一点零钱

[MarshalAs]在这里没有扮演任何角色,只有pinvoke marshaler关注它。您需要使用来获取存储在堆栈上的数组。小心不要将其索引超出范围。而且要小心,当您刚接触C#时,过早优化代码太容易了。当您尝试GC时,您只会感觉到它的效率有多高。@HansPassant这不是优化,只是常识而已。但我不能使用固定的缓冲区,因为它只适用于原始类型:/知道C或C++不是一种资产,你会得到错误的常识。C#有它自己的,它看起来不像那样。@HansPassant对不需要外部引用的数据使用堆栈有什么不对?如果您知道移动语义的含义,那么您必须熟悉堆栈缓冲区溢出引起的问题。不仅是UB,还有恶意软件如何利用它。那有点危险。但是请随意使用您的方式,我今天不需要说服您。VB.NET的语法是
publics1()作为TestValue
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();
    }
}