2011-02-03 48 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

是,这个工程:

​​