通过 COM4J 从 .NET 方法返回接口数组
2022-09-02 11:03:40
如何通过 COM4J 将对象数组(实现 COM 接口)从 C# 方法返回到 Java 方法?
生成数组的示例 C# 类:
using System;
using System.Runtime.InteropServices;
namespace Example
{
[ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAnimal
{
string Speak();
}
[ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IFarm
{
[return:MarshalAs(UnmanagedType.SafeArray,
SafeArraySubType=VarEnum.VT_UNKNOWN)]
IAnimal[] GetAnimals();
}
[ComVisible(true), ClassInterface(ClassInterfaceType.None)]
public class Farm : IFarm
{
public IAnimal[] GetAnimals()
{
return new IAnimal[] { new Cow(), new Pig() };
}
}
internal class Cow: IAnimal
{
public string Speak()
{
return "Moo";
}
}
internal class Pig: IAnimal
{
public string Speak()
{
return "Oink";
}
}
}
生成的 .tlb 中的接口声明如下所示:
[
odl,
uuid(1FB5E376-E78D-3A2E-BEF3-F3C798FCF44C),
version(1.0),
oleautomation,
custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "Example.IFarm")
]
interface IFarm : IUnknown
{
HRESULT _stdcall GetAnimals([out, retval] SAFEARRAY(IUnknown*)* pRetVal);
};
Java 客户端代码:
import com4j.*;
public class Example {
public static void main(String[] args) {
IFarm farm = ClassFactory.createFarm();
Com4jObject[] animals = farm.getAnimals();
for (Com4jObject o: animals) {
IAnimal animal = o.queryInterface(IAnimal.class);
if (animal != null) {
animal.speak();
}
}
}
}
这编译,但我在运行时得到这个异常:
Exception in thread "main" com4j.ComException:
unexpected conversion type: 500 : .\invoke.cpp:470
at com4j.Wrapper.invoke(Wrapper.java:185)
at $Proxy5.getAnimals(Unknown Source)
at MainClass.main(MainClass.java:7)
Caused by: com4j.ComException: unexpected conversion type: 500 : .\invoke.cpp:470
at com4j.Native.invoke(Native Method)
at com4j.StandardComMethod.invoke(StandardComMethod.java:35)
at com4j.Wrapper$InvocationThunk.call(Wrapper.java:354)
at com4j.Task.invoke(Task.java:55)
at com4j.ComThread.run0(ComThread.java:157)
at com4j.ComThread.run(ComThread.java:137)
我尝试过的其他事情:
- 编组为 而不是
(这会引发相同的异常。SAFEARRAY(VARIANT)*
SAFEARRAY(IUnknown*)*
- 删除属性( 无法创建代理方法)
MarshalAs
tlbimp
有没有办法封送数组,以便COM4J可以将其转换为有效的Java数组?
或者,有没有办法在Java中分配数组并允许.NET方法填充它?(我尝试了此操作,但.NET方法收到数组的副本,并且Java代码永远不会看到插入到副本中的对象。也许有一种方法可以覆盖它?
编辑:这可能与 https://stackoverflow.com/a/6340144/12048 - VBScript似乎可以实现类似的事情