在C#中使用带有COM互操作的ref Array参数

Ste*_*ser 5 c# com interop com-interop

我有一个第三方COM库,我正在消耗,并且我遇到了数组参数问题.

我正在调用的方法签名如下:

int GetItems(ref System.Array theArray)
Run Code Online (Sandbox Code Playgroud)

文档说该方法的返回值是它将填充到数组中的项目数,但是当它被调用时,数组中的所有值都只是默认值(它们是结构体),即使该方法返回非零回报值.

我知道这里有一些时髦的COM互操作,但我真的没有多少经验,也无法搞清楚.这就是我试图访问它的方式:

Array items = Array.CreateInstance(typeof(structItem), 100);
int numberOfItems = instance.GetItems(items);

Array items = Array.CreateInstance(typeof(structItem), 100);
int numberOfItems = instance.GetItems(ref items);

structItem[] items = new structItem[100];
int numberOfItems = instance.GetItems(items);

structItem[] items = new structItem[100];
int numberOfItems = instance.GetItems(ref items);
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

更新:我认为它可能与SafeArrays有关,如下所述:http://www.west-wind.com/Weblog/posts/464427.aspx 区别在于我应该传入数组ref,不只是处理返回值.本文的具体解决方案不起作用,但我觉得我变暖了.

Han*_*son 0

我已经有一段时间没有进行任何互操作了,所以我不确定,但我认为您应该分配非托管内存以发送到 COM 库。Marshal我会特别查看该类Marshal.AllocHGlobal(不过,您可能必须使用FreeHGlobal它来释放内存)。

也许是这样的:

IntPtr p = Marshal.AlloHGlobal(items.Length * Marshal.SizeOf(typeof(structItem));  
Marshal.Copy(items, 0, p, items.Length);  
Run Code Online (Sandbox Code Playgroud)