在具有COM互操作的C#中使用ref数组参数

在具有COM互操作的C#中使用ref数组参数,c#,com,interop,com-interop,C#,Com,Interop,Com Interop,我有一个正在使用的第三方COM库,在数组参数方面有问题 我正在调用的方法签名如下所示: int GetItems(ref System.Array theArray) 文档中说,该方法的返回值是它将填充到数组中的项数,但是当调用它时,数组中的所有值都只是默认值(它们是结构),即使该方法返回的返回值不是零 我知道这里有一些时髦的COM互操作的东西,但我真的没有太多的经验,也无法理解。以下是我尝试访问它的方式: Array items = Array.CreateInstance(typeof(s

我有一个正在使用的第三方COM库,在数组参数方面有问题

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

int GetItems(ref System.Array theArray)
文档中说,该方法的返回值是它将填充到数组中的项数,但是当调用它时,数组中的所有值都只是默认值(它们是结构),即使该方法返回的返回值不是零

我知道这里有一些时髦的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);
我做错了什么


更新:我认为这可能与safearray有关,如下所述:区别在于我应该通过ref传入数组,而不仅仅是处理返回值。本文中的特定解决方案不起作用,但我感觉我越来越热了。

我已经有一段时间没有进行任何互操作了,所以我不确定,但我认为您应该分配非托管内存以发送到COM库。我将查看
封送
类,尤其是
封送.AllocHGlobal
(您可能需要使用
FreeHGlobal
来释放内存)

可能是这样的:

IntPtr p = Marshal.AlloHGlobal(items.Length * Marshal.SizeOf(typeof(structItem));  
Marshal.Copy(items, 0, p, items.Length);