我如何在C#中为Office Com Proxy方法创建委托?

时间:2013-02-07 05:02:45

标签: c# com interop

问题与以下主题有关: Access COM vtable from C#

我要做的是通过c#

中的方法指针从com对象调用方法

我知道方法指针不是必需的,但在这种特殊情况下它是。

为什么我需要方法指针?

我希望通过后期绑定从Word.Content Control访问SetPlaceholderText方法。 .NET-> COM中的所有后期绑定功能都使用IDispatch接口中的Invoke方法,该方法是从com对象实现的。 Word.ContentControl类中的Invoke方法有一个错误!它工作早期绑定因为interop运行时避免Invoke和使用方法指针。 (这就是我想要处理的问题)。它无法使用vb latebinding,c#dynamics或GetType()方法。调用...

我使用链接发布的代码作为模板:

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void SetPlaceHolderTextCallback(
      [MarshalAs(28)] [In] object BuildingBlock = null,
      [MarshalAs(28)] [In] object Range = null, 
      [MarshalAs(19)] [In] string Text = "");

object contentControl = GetContentControlProx();
IntPtr comPtr = Marshal.GetComInterfaceForObject(contentControl,
                                         typeof(ContentControl));
IntPtr vTable = Marshal.ReadIntPtr(comPtr); 

int start = Marshal.GetStartComSlot(typeof(ContentControl));
int end = Marshal.GetEndComSlot(typeof(ContentControl));

SetPlaceHolderTextCallback invoker = null;
ComMemberType mType = MemberTypes.Method;
for (int i = start; i < end; i++)
{
   System.Reflection.MemberInfo mi = 
   Marshal.GetMethodInfoForComSlot(typeof(ContentControl), i, ref mType);
   if (mi.Name == "SetPlaceholderText")
   {
      IntPtr methodPointer = Marshal.ReadIntPtr(vTable, i * 
                                  Marshal.SizeOf(typeof(IntPtr)));
      invoker = Marshal.GetDelegateForFunctionPointer(methodPointer,
      typeof(SetPlaceHolderTextCallback)) as SetPlaceHolderTextCallback;
      break;
   }
}

invoker(Type.Missing, Type.Missing, "helloWorld");

调用因AccessViolationException而失败。我现在不知道......

1 个答案:

答案 0 :(得分:0)

好像我的问题已经解决了。 来自jochen manns的博客文章给了我答案。 第一个参数必须是类intance的IntPtr。

<!-- language: lang-cs -->
    IntPtr adressPointer = Marshal.GetComInterfaceForObject(control, 
                                    typeof(Word.ContentControl));
    invoker(adressPointer, null, null, "helloWorld");
<!-- language: lang-cs -->

工作!!!