【问题标题】:C# + COM, modify array in parameterC# + COM,修改参数中的数组
【发布时间】:2010-09-20 11:02:12
【问题描述】:

我有一个 C# 中的 COM 对象和一个 Silverlight 应用程序(升级权限),它是该 COM 对象的客户端。

COM 对象:

[ComVisible(true)]
public interface IProxy
{
    void Test(int[] integers);
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Proxy : IProxy
{
    [ComVisible(true)]
    public void Test(int[] integers)
    {
        integers[0] = 999;
    }    
}

Silverlight 客户端:

dynamic proxy = AutomationFactory.CreateObject("NevermindComProxy.Proxy");

int[] integers = new int[5];
proxy.Test(integers);

我期望整数 [0] == 999,但数组是完整的。

如何让COM对象修改数组?

UPD 适用于非 Silverlight 应用程序。 Silverlight 失败。 Silverlight如何修复?

【问题讨论】:

  • 为什么使用 COM 作为 2 个 .NET 程序集之间的互操作性引擎?也许您应该改用 Assembly.Load?
  • 目标是使用来自silverlight 应用程序的本机代码。所以我做了silverlight -> COMProxy -> 本机代码。据我了解,silverlight 无法从其沙箱中调用本机代码。如果我错了,请纠正我。
  • 这超出了我的知识范围,抱歉。祝你找到答案好运!

标签: c# com interop com-interop


【解决方案1】:

简短的回答是您需要通过 ref 传递数组(请参见示例上方的 AutomationFactory 中的注释 [数组在 C# 中按值传递]) - 那么问题是,SL 会因参数异常而出错当您致电proxy.Test(ref integers) 时(我不知道为什么)。解决方法是,如果方法通过 ref 获取对象,则 SL 将通过 ref 传递数组,所以这可行...

[ComVisible(true)]
public interface IProxy
{
    void Test( ref object integers);
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Proxy : IProxy
{
    [ComVisible(true)]
    public void Test(ref object intObj)
    {
        var integers = (int[])intObj;
        integers[0] = 999;
    }
}

并且在 SL 代码中添加 ref 如下:

dynamic proxy = AutomationFactory.CreateObject("NevermindComProxy.Proxy");

var integers = new int[5];
proxy.Test( ref integers);

从调用者或接口定义中删除 ref,它不会更新数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多