2014-01-31 26 views
1

我一直在考慮嘗試使用實現OPOS服務對象的C#編寫COM對象。我使用Automation和MFC在C++中完成了它,並沒有太困難。所以我被困在試圖轉換它的一種方法上。我會排除接口中的其他方法,因爲它們很簡單(或者我希望)。如何將IDispatch *置於託管代碼

[id(6), helpstring("method OpenService")] 
LONG OpenService(BSTR lpclDevClass, BSTR lpclDevName, IDispatch* lpDispatch); 

我的C#代碼看起來像這樣到目前爲止,但我堅持在OpenService。

[ComVisible(true)] 
[Guid("76F8309C-3837-4065-960F-BE156383896D")] 
[ClassInterface(ClassInterfaceType.AutoDispatch)] 
public class IErtMSR 
{ 
    [DispId(1)] 
    int COFreezeEvents([MarshalAs(UnmanagedType.VariantBool)] bool Freeze); 
    [DispId(2)] 
    int GetPropertyNumber([In] int lPropIndex); 
    [DispId(3)] 
    void SetPropertyNumber([In] int lPropIndex, [In] int nNewValue); 
    [DispId(4), MarshalAs(UnmanagedType.BStr)] 
    string GetPropertyString([In] int lPropIndex); 
    [DispId(5)] 
    void SetPropertyString([In, MarshalAs(UnmanagedType.BStr)] string StringData); 
    [DispId(6)] 
    int OpenService([In, MarshalAs(UnmanagedType.BStr)] string lpclDevClass, [In, MarshalAs(UnmanagedType.BStr)] string lpclDevName, IDispatch* lpDispatch); 
    //...the rest of the 24 methods. 
} 

正如您所見,我不知道要爲IDispatch *放置什麼。我在這種情況下使用什麼?

+0

我想通了。我不得不創建一個IDispatch方法(我發現Hans Persant有這個可用..)現在我只是要弄清楚如何從它調用一個事件.. :) –

回答

1

您不需要爲COM IDispatch創建託管定義或明確實現其成員。該框架有一個內置的支持。只要聲明你的OpenService是這樣的:

[DispId(6)] 
int OpenService(
    [In, MarshalAs(UnmanagedType.BStr)] string lpclDevClass, 
    [In, MarshalAs(UnmanagedType.BStr)] string lpclDevName, 
    [In, MarshalAs(UnmanagedType.IDispatch] object lpDispatch); 
+0

在我的腦海中,我看到這工作得很好,但簽名說IDispatch *。我不應該讓'ref object lpDispatch'? –

+0

@RobertSnyder,no,'ref object'意味着可以從調用中返回一個'IDispatch'對象。這將映射到IDL中的[in,out] IDispatch ** p'。只要確保你傳遞的''object'實現了'IDispatch'兼容的接口,例如:'[InterfaceType(ComInterfaceType.InterfaceIsDual)] ITest {/ * ... * /}'你也可以使用'[ClassInterface (ClassInterfaceType.AutoDispatch/AutoDual)]'在對象的''class'上,但是我會堅持一個獨立的接口,如'ITest'和'[ComDefaultInterface(typeof(ITest))]''在類上。 – Noseratio