从C#访问COM虚函数表

从C#访问COM虚函数表

本文介绍了从C#访问COM虚函数表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C#中的任何方式来访问,以获得一个函数的地址的COM对象的虚方法表?

Is there any way in C# to access a COM object's virtual method table in order to get a function's address?

推荐答案

很多搜索和拼凑不同部分的解决方案之后,我想通了,如何做到这一点。

After a lot of searching and piecing together different partial solutions, I figured out how to do it.

首先,你需要定义你想访问该对象的COM组件类:

First you need to define the COM coclass for the object you're trying to access:

[ComImport, Guid("..."), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface ISomeCOMInterface
{
   // Define interface methods here, using PInvoke conversion between types
}

接下来,您需要实例化COM对象。有几个方法可以做到这一点。由于我在DirectSound的很感兴趣,我用:

Next you need to instantiate the COM object. There are a couple of ways to do that. Since I was interested in DirectSound, I used:

[DllImport("dsound.dll", EntryPoint = "DirectSoundCreate", ...]
static extern void DirectSoundCreate(IntPtr GUID, [Out, MarshalAs(UnmanagedType.Interface)] out IDirectSound directSound, IntPtr pUnkOuter);

IDirectSound directSound;
DirectSoundCreate(IntPtr.Zero, out directSound, IntPtr.Zero);

既然现在我有我的COM对象,我然后可以使用 Marshal.GetComInterfaceForObject的汉斯建议()

Since I now had my COM object, I could then use Hans' suggestion of Marshal.GetComInterfaceForObject():

IntPtr comPtr = Marshal.GetComInterfaceForObject(directSound, typeof(IDirectSound));
IntPtr vTable = Marshal.ReadIntPtr(comPtr);

作为额外的奖励,你就可以通过类似这样的虚函数表的功能迭代:

As an added bonus, you can then iterate through the vtable functions like this:

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

ComMemberType mType = 0;
for (int i = start; i < end; i++)
{
    System.Reflection.MemberInfo mi = Marshal.GetMethodInfoForComSlot(typeof(IDirectSound), i, ref mType);
    Console.WriteLine("Method {0} at address 0x{1:X}", mi.Name, Marshal.ReadIntPtr(vTable, i * Marshal.SizeOf(typeof(IntPtr))).ToInt64());
}



额外的阅读/参考:

Extra Reading / References:


  • [信息上的COM组件类声明]

  • 的 [信息上的VTable和COM一般]

  • [信息具体到DirectSound的COM接口]

  • http://msdn.microsoft.com/en-us/library/aa645736(VS.71).aspx [Info on COM coclass declarations]
  • http://www.codeproject.com/KB/COM/com_in_c1.aspx [Info on VTables and COM in general]
  • http://naudio.codeplex.com/ [Info specific to the DirectSound COM Interfaces]

这篇关于从C#访问COM虚函数表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:19