开发者

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

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 ob开发者_StackOverflowjects.)

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜