P /从C到C#调用,不知道数组的大小

正确地知道我的代码我已经将结构声明为这样,修复了这个16,在编译时知道。

struct CONSOLE_SCREEN_BUFFER_INFOEX { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public int ColorTable[]; } 

但我需要的是能够拥有这种结构:

 struct CONSOLE_SCREEN_BUFFER_INFOEX { int arraySize; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0)] public int ColorTable[]; } 

从C函数响应中获取arraySize,初始化具有适当大小的ColorTable数组,将响应结果放入ColorTable。

不确定是否可能,现在就进行调查,并且非常欢迎任何评论。

您可以使用Marshal类通过一些手动编组轻松地完成此操作。 例如:

 [DllImport(@"MyLib.dll")] private static extern void Foo(IntPtr structPtr); private static IntPtr StructPtrFromColorTable(int[] colorTable) { int size = sizeof(int) + colorTable.Length*sizeof(int); IntPtr structPtr = Marshal.AllocHGlobal(size); Marshal.WriteInt32(structPtr, colorTable.Length); Marshal.Copy(colorTable, 0, structPtr + sizeof(int), colorTable.Length); return structPtr; } private static int[] ColorTableFromStructPtr(IntPtr structPtr) { int len = Marshal.ReadInt32(structPtr); int[] result = new int[len]; Marshal.Copy(structPtr + sizeof(int), result, 0, len); return result; } static void Main(string[] args) { int[] colorTable = new int[] { 1, 2, 3 }; IntPtr structPtr = StructPtrFromColorTable(colorTable); try { Foo(structPtr); colorTable = ColorTableFromStructPtr(structPtr); } finally { Marshal.FreeHGlobal(structPtr); } }