我有一个.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错误0x80020005(显示类型不匹配)。我知道我的方法被正确调用了,只是当.net/com转到marshall返回时,它会阻塞。如我所说,它可以很好地处理整数或字符串数组。我必须对类做什么才能允许它在数组中返回?
碰巧的是,我的类只包含几个字符串和一个int(没有方法),如果这样做容易的话。显然,我尝试返回一个非空数组和实际包含一些数据的类,这只是说明问题的最简单情况。