【问题标题】:Using ref Array parameters in C# with COM interop将 C# 中的 ref Array 参数与 COM 互操作一起使用
【发布时间】:2011-02-08 15:09:41
【问题描述】:

我有一个正在使用的第 3 方 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);

我做错了什么?

更新:我认为这可能与 SafeArrays 有关,如下所述:http://www.west-wind.com/Weblog/posts/464427.aspx 不同之处在于我应该通过 ref 传入数组,而不仅仅是处理返回值。这篇文章的具体解决方法不行,但是感觉自己越来越暖和了。

【问题讨论】:

    标签: c# com interop com-interop


    【解决方案1】:

    自从我做任何互操作以来已经有一段时间了,所以我不确定,但我认为你应该分配非托管内存以发送到 COM 库。我会查看Marshal 类,尤其是Marshal.AllocHGlobal(你可能必须使用FreeHGlobal 来释放内存)。

    可能是这样的:

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

    【讨论】:

      猜你喜欢
      • 2010-11-12
      • 1970-01-01
      • 2014-09-03
      • 2011-02-01
      • 2011-07-02
      • 1970-01-01
      • 2012-06-26
      • 2010-12-27
      • 1970-01-01
      相关资源
      最近更新 更多