在閱讀了無數關於從C#訪問COM對象的問題之後,似乎沒有任何東西可以解決我的問題。我用C++創建了一個COM對象併成功註冊了它。 OLEView可以看到並創建我的對象的一個實例。我也可以創建它的一個實例,並用一個簡單的單獨的C++應用程序調用它的方法。C#無法查看或使用COM對象的方法
在C#中,我已經添加了DLL在參考管理器 - > COM - >類型庫,而且似乎能夠創建對象(名爲咖啡)的一個實例:
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共類:
...
[
uuid(D857715A-BEB9-4436-BBB7-1143F651196C)
]
coclass Coffee
{
[default] interface ICoffee;
[default, source] dispinterface _ICoffeeEvents;
};
這個對象包含一個成員變量「盎司」,一個的get_和put_,以及一個名爲TestMethod的方法,什麼也不做,除了返回S_OK。所有可以從C++調用。在C#中,intellisense除了「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#完全使用該對象?
編輯: ICoffee中的.idl:
[
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
@Victor增加ICoffee – giraffee
可能你應該使用ICoffee xx =(ICoffee)obj;而不是咖啡xx =(咖啡)obj;? – Victor