【问题标题】:Marshal size const array元帅大小 const 数组
【发布时间】:2019-05-16 10:21:48
【问题描述】:

我正在尝试在结构中分配堆栈数组。好吧,我的意思是指针。但我希望在没有额外代码的情况下完成分配,因为我在编写代码时知道大小(我不想在创建结构时做一堆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];
}

【问题讨论】:

  • [MarshalAs] 在这里没有任何作用,只有 pinvoke marshaler 关注它。您需要使用fixed size buffer 来获取存储在堆栈中的数组。小心不要索引它超出范围。并且要小心,当您不熟悉 C# 时,过早地优化代码太容易了。您只有在尝试时才能感受到 GC 的效率。
  • @HansPassant 这不是优化,只是这里的常识。但我不能使用固定缓冲区,因为它仅适用于原始类型:/
  • 很好地了解 C 或 C++ 并不完全是一种资产,您会得到错误的常识。 C#有它自己的,它看起来不像。
  • @HansPassant 将堆栈用于不需要外部引用的数据有什么错误?
  • 如果你知道move语义是什么意思,那么你一定很熟悉栈缓冲区溢出带来的问题。不仅是 UB,还有恶意软件的可利用性。那种危险。但是请随意按照自己的方式去做,我今天不需要说服你。

标签: c# marshalling stack-allocation


【解决方案1】:
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();
    }
}

最后我只需要一点点改变!

【讨论】:

  • VB.NET 的语法是&lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=128)&gt; Public s1() As TestValue
猜你喜欢
  • 1970-01-01
  • 2011-05-24
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多