【问题标题】:How to return an array of .NET objects via a COM method如何通过 COM 方法返回 .NET 对象数组
【发布时间】:2011-11-30 04:43:10
【问题描述】:

我有一个 .NET 程序集。它恰好是用 C++/CLI 编写的。我正在通过 COM 公开一些对象。一切正常,但我一生都无法弄清楚如何从方法中返回我自己的对象数组。每次我这样做时,我都会在运行时收到类型不匹配错误。我可以返回一个整数或字符串数​​组就好了。

这是我的主要课程

[Guid("7E7E69DD-blahblah")]
[ClassInterface(ClassInterfaceType::None)]
[ComVisible(true)]
public ref class Foo sealed : IFoo
{
public:
    virtual array<IBar^>^ GetStuff();
}

[Guid("21EC1AAA-blahblah")]
[InterfaceType(ComInterfaceType::InterfaceIsIDispatch)]
[ComVisible(true)]  
public interface class IFoo
{
public:
    virtual array<IBar^>^ GetStuff()
    {
        // For simplicity, return an empty array for now.
        return gcnew array<IBar^>(0);
    }
};

这是我要返回的课程

[Guid("43A37BD4-blahblah")]
[InterfaceType(ComInterfaceType::InterfaceIsIDispatch)]
[ComVisible(true)]  
public interface class IBar
{
    // Completely empty class, just for testing.  
    //In real life, I would like to return two strings and an int.
};

[Guid("634708AF-blahblah")]
[ClassInterface(ClassInterfaceType::None)]
[ComVisible(true)]
[Serializable]
public ref class Bar : IBar
{
};

这是我调用它的(本机)C++ 代码:

MyNamespace::IFooPtr session(__uuidof(MyNamespace::Foo));
// For simplicity, don't even check the return.
session->GetStuff();

调用 GetStuff() 得到一个 _com_error 0x80020005 (DISP_E_TYPEMISMATCH)。我可以告诉我的方法被正确调用了,只是当 .NET/COM 去编组返回时,它会窒息。正如我所说,它适用于整数或字符串数​​组。我必须对我的班级做些什么才能让它在数组中返回?

碰巧,我的类将只包含几个字符串和一个 int(无方法),如果这样更容易的话。显然我已经尝试返回一个非空数组和实际包含一些数据的类,这只是说明问题的最简单的情况。

【问题讨论】:

    标签: .net com c++-cli com-interop safearray


    【解决方案1】:

    你需要实现IDispatchEnumerator方法

    public ref class FooCollection{
    [DispId(-4)]
    public IEnumerator^ GetEnumerator()
    {
    //...
    }
    }
    

    【讨论】:

    • 所以我不能只返回一个数组,我必须编写自己的集合类并公开它?令人失望,但我想不会太难。
    • @mhenry1384,如果this answer 是正确的,那么应该是可能的。
    猜你喜欢
    • 2014-09-29
    • 1970-01-01
    • 2011-09-14
    • 2012-09-24
    • 2020-10-13
    • 2011-08-05
    • 2011-03-05
    • 2010-11-26
    • 1970-01-01
    相关资源
    最近更新 更多