在C#中是否可以使用我未分配的内存?还是可以更改已经创建的数组的大小(但不分配内存)?
这是我的解决方案。这是更好的方法吗?
using System.Runtime.InteropServices;
class LengthOfArray
{
public int Length;
}
[StructLayout(LayoutKind.Explicit)]
class MyArray
{
[FieldOffset(0)]
public LengthOfArray LengthOfArray;
[FieldOffset(0)]
public byte[] Array = new byte[4];
}
internal class Program
{
private static void Main(string[] args)
{
var arr = new MyArray();
arr.LengthOfArray.Length = 1024;
}
}
以及如何最好地对弦进行类似的处理?
这不会按照您认为的那样做:
[FieldOffset(0)]
public byte[] Array = new byte[4];
这会将指针指向偏移量为零的数组。它不会在此处放置4个元素。
我无法告诉您您应该做什么,因为我不知道您想完成什么。如果您需要一个可变大小的结构,请使用所需的任何方法(Marshal.AllocHGlobal
或固定方法byte[]
)分配一个字节块。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句