将动态大小数组编组到struct中(Marshalling dynamic size array into struct)
如何定义具有动态大小数组的结构?
这样对吗?
struct MyStruc { public int len; [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] public int buf[]; }how can i define a struct with a dynamic sized array?
is it right?
struct MyStruc { public int len; [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] public int buf[]; }最满意答案
假设您需要一个包含指向数组的指针的结构。
将指向数组的指针声明为IntPtr并使用Marshal.AllocHGlobal , Marshal.Copy等手动编组数组内容。
假设您需要一个可变大小的结构而不是包含指向该数组的指针的结构。
您不能使用p / invoke封送变量大小的结构。 您至少有以下两个选项:
将结构分成两个参数。 使用Marshal.AllocHGlobal , Marshal.Copy等手动Marshal.AllocHGlobal结构。Assuming that you want a struct containing a pointer to the array.
Declare the pointer to the array as IntPtr and marshal the array contents manually with Marshal.AllocHGlobal, Marshal.Copy etc.
Assuming that you want a variable sized struct rather than a struct containing a pointer to the array.
You cannot marshal a variable sized struct using p/invoke. You have at least these two options:
Break the struct into two parameters. Marshal the struct manually with Marshal.AllocHGlobal, Marshal.Copy etc.更多推荐
发布评论