COM互操作:我如何从LPDISPATCH获得CCW?

时间:2011-02-03 17:13:32

标签: c# com interop winfax

我正在用C#编写一个应用程序,它通过IDispatch连接到一个旧的skool COM对象。我用这种代码做到了这一点:

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);

1 个答案:

答案 0 :(得分:0)

是的,这有效:

    Type type = Type.GetTypeFromProgID("WinFax.Attachments");
    if (type == null)
          throw new ArgumentException("WinFax Pro is not installed.");
    Object comObject = Activator.CreateInstance(type);  
    Object o2 = type.InvokeMember("MethodReturnsLpdispatch",
                                     BindingFlags.InvokeMethod,
                                     null,
                                     comObject,
                                     null);
    Type t2 = Type.GetTypeFromProgID("WinFax.Attachment"); // different ProgId !!
    Object x = t2.InvokeMember("MethodOnSecondComObject",  
                                     BindingFlags.InvokeMethod,
                                     null,
                                     o2,
                                     null);