2009-11-16 60 views
2

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

这里是我的主类

[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(没有方法),如果这样做更容易。显然我试过返回一个非空数组和实际包含一些数据的类,这只是说明问题的最简单的例子。

回答

0

您需要实现IDispatchEnumerator方法

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

所以我不能只返回一个数组,我写我自己的集合类和揭露是什么?令人失望,但我想不太难。 – mhenry1384 2009-11-18 18:21:43

+0

@ mhenry1384,如果[这个答案](http://stackoverflow.com/a/6340144/12048)是正确的,那么它应该是可能的。 – finnw 2012-10-03 15:23:45

相关问题