2011-02-03 47 views
0

我正在用C#編寫一個應用程序,它通過IDispatch連接到一個old-skool COM對象。我這樣做是有這種代碼:COM互操作:如何從LPDISPATCH獲取CCW?

public sealed class Attachments 
{ 
    Object comObject; 
    Type type; 

    private readonly static Attachments _instance = new Attachments(); 
    public static Attachments Instance { get { return _instance; } } 

    private Attachments() 
    { 
     type = Type.GetTypeFromProgID("WinFax.Attachments"); 
     if (type == null) 
      throw new ArgumentException("WinFax Pro is not installed."); 
     comObject = Activator.CreateInstance(type); 
    } 

    public Int16 Count() 
    { 
     Int16 x = (Int16) type.InvokeMember("Count", 
              BindingFlags.InvokeMethod, 
              null, 
              comObject, 
              null); 
     return x; 
    } 
    .... 

一本IDispatch接口的方法返回一個LPDISPATCH,我把它是一個長指針到IDispatch接口。它是另一個COM對象,ProgId WinFax.Attachment。 (WinFax.Attachments管理WinFax.Attachment對象的集合。)

在C#中,如何在對應於該LPDISPATCH的COM對象上調用方法?我可以做這樣的事情:

Object o = type.InvokeMember("MethodReturnsLpdispatch", 
            BindingFlags.InvokeMethod, 
            null, 
            comObject, 
            null); 
    Type t2 = Type.GetTypeFromProgID("WinFax.Attachment"); // different ProgId !! 
    Object x = t2.InvokeMember("MethodOnSecondComObject", 
            BindingFlags.InvokeMethod, 
            null, 
            o, 
            null); 
+0

使用o.GetType()。請在這裏借用或竊取使用* dynamic *關鍵字。或者在VB.NET中寫一個適配器。 – 2011-02-03 17:22:28

回答

0

是,這個工程:

​​