COM interop: How can I get the CCW from an LPDISPATCH?

1k views Asked by At

I am writing an app in C#, that connects to an old-skool COM object via IDispatch. I do this with this sort of code:

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;
    }
    ....

One of the methods on this IDispatch interface returns an LPDISPATCH, which I take it is a Long Pointer to IDispatch. It is another COM object, ProgId WinFax.Attachment. (WinFax.Attachments manages a collection of WinFax.Attachment objects.)

In C#, How do I call methods on the COM object corresponding to that LPDISPATCH? Can I just do something like this:

    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

There are 1 answers

0
Cheeso On BEST ANSWER

yes, this works:

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