How to invoke a method of a private COM interfaces, defined in a base class?

前端 未结 4 805
暗喜
暗喜 2020-12-20 04:01

How can I invoke a method of a private COM interface, defined in a base class, from a derived class?

For example, here is the COM interface, IComInterface

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-20 04:08

    Here is my solution. Ok, it uses reflection, but I don't see where is the problem since it's much simpler, and the final usage is really just one line of code, like this:

    // IComInterface
    void IComInterface.ComMethod(object arg)
    {
        InvokeBaseMethod(this, "ComMethod", typeof(OldLibrary.BaseClass), typeof(IComInterface), arg);
    }
    

    and the utility method (reusable for any class) is this:

    public static object InvokeBaseMethod(object obj, string methodName, Type baseType, Type equivalentBaseInterface, params object[] arguments)
    {
        Type baseInterface = baseType.GetInterfaces().First((t) => t.GUID == equivalentBaseInterface.GUID);
        ComMemberType type = ComMemberType.Method;
        int methodSlotNumber = Marshal.GetComSlotForMethodInfo(equivalentBaseInterface.GetMethod(methodName));
        MethodInfo baseMethod = (MethodInfo)Marshal.GetMethodInfoForComSlot(baseInterface, methodSlotNumber, ref type);
        return baseMethod.Invoke(obj, arguments);
    }
    

提交回复
热议问题