【发布时间】:2015-11-03 04:23:25
【问题描述】:
在阅读了无数关于从 C# 访问 COM 对象的问题后,似乎没有任何问题可以解决我的问题。我在 C++ 中创建了一个 COM 对象并成功注册了它。 OLEView 可以查看并创建我的对象的实例。我还能够创建它的一个实例并使用一个简单的单独 C++ 应用程序调用它的方法。
在 C# 中,我在 Reference Manager -> COM -> Type Libraries 中添加了 DLL,并且似乎能够创建对象的实例(名为 Coffee):
System.Guid g = new System.Guid("D857715A-BEB9-4436-BBB7-1143F651196C");
Type myType = Type.GetTypeFromCLSID(g);
dynamic obj = Activator.CreateInstance(myType);
Coffee xx = (Coffee)obj;
GUID 代表 COM 对象在我的 .idl 中的 coclass:
...
[
uuid(D857715A-BEB9-4436-BBB7-1143F651196C)
]
coclass Coffee
{
[default] interface ICoffee;
[default, source] dispinterface _ICoffeeEvents;
};
该对象包含一个成员变量“ounces”、一个 get_ 和 put_,以及一个名为 TestMethod 的方法,该方法除了返回 S_OK 之外什么都不做。所有都可以从 C++ 调用。在 C# 中,智能感知除了对象的“int ICoffee.Ounces”之外什么都看不到。 get_ 和 put_ 不显示,TestMethod 也不显示。
我也尝试过 Type.GetMethod("TestMethod") 并对其进行调用,但 MethidInfo 最终为空:
MethodInfo testMethod = myType.GetMethod("TestMethod");
object value = testMethod.Invoke(obj, new object[] { });
还尝试在动态对象上调用它:
obj.TestMethod();
Additional information: 'System.__ComObject' does not contain a definition for 'TestMethod'
我到底错过了什么不让 C# 完全使用该对象?
编辑: .idl 中的 ICoffee:
[
object,
uuid(35B4618D-733B-453D-9714-FFCB35740FB2),
dual,
nonextensible,
pointer_default(unique)
]
interface ICoffee : IDispatch{
[propget, id(1)] HRESULT Ounces([out, retval] LONG* pVal);
[propput, id(1)] HRESULT Ounces([in] LONG newVal);
[id(2)] HRESULT GetOunces([in] LONG* nOunces);
[id(3), helpstring("This is a test method")] HRESULT TestMethod();
};
【问题讨论】:
-
你能显示ICoffee的描述吗?
-
@Victor 添加了 ICoffee
-
也许你应该使用 ICoffee xx = (ICoffee)obj;而是 Coffee xx = (Coffee)obj;?