将动态大小数组编组为struct [英] Marshalling dynamic size array into struct
本文介绍了将动态大小数组编组为struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何定义具有动态大小的数组的结构?
how can i define a struct with a dynamic sized array?
对吗?
struct MyStruc {
public int len;
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)]
public int buf[];
}
推荐答案
假设您想要一个包含指向数组的指针的结构.
将指向数组的指针声明为IntPtr
,并使用Marshal.AllocHGlobal
,Marshal.Copy
等手动编组数组内容.
Declare the pointer to the array as IntPtr
and marshal the array contents manually with Marshal.AllocHGlobal
, Marshal.Copy
etc.
假设您要使用可变大小的结构,而不是包含指向数组的指针的结构.
您不能使用p/invoke封送可变大小的结构.您至少有以下两个选择:
You cannot marshal a variable sized struct using p/invoke. You have at least these two options:
- 将该结构分为两个参数.
- 使用
Marshal.AllocHGlobal
,Marshal.Copy
等手动编组结构.
- Break the struct into two parameters.
- Marshal the struct manually with
Marshal.AllocHGlobal
,Marshal.Copy
etc.
这篇关于将动态大小数组编组为struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文