2009-11-16 92 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

相關問題