如何获得指向接口的指针?

Kas*_*sen 5 c# interop

我正在尝试执行此功能:

public static int QueryInterface(
    IntPtr pUnk,
    ref Guid iid,
    out IntPtr ppv
)
Run Code Online (Sandbox Code Playgroud)

在哪里

pUnk
Type: System.IntPtr
The interface to be queried.
Run Code Online (Sandbox Code Playgroud)

基本上,Marshal.QueryInterface 从 COM 对象请求一个指向指定接口的指针。我想查询许多接口(全部来自 IPersist),那么我如何获取指向这些接口的引用指针呢?

注意:IPersistStorage 就是其中之一。

编辑(这有效):

// Use the CLSID to instantiate the COM object using interop.
Type type = Type.GetTypeFromCLSID(myGuid);
Object comObj = Activator.CreateInstance(type);

// Return a pointer to the objects IUnknown interface.
IntPtr pIUnk = Marshal.GetIUnknownForObject(comObj);
IntPtr pInterface;
Int32 result = Marshal.QueryInterface(pIUnk, ref myGuid, out pInterface);
Run Code Online (Sandbox Code Playgroud)

Jef*_*ado 3

阅读页面备注部分的最后一行Marshal.QueryInterface()

QueryInterface 方法公开COM 对象的IUnknown::QueryInterface方法,该方法尝试获取特定的接口指针。[...] 要获取表示IUnknown接口指针的IntPtr值,您可以调用Marshal.GetComInterfaceForObjectMarshal.GetIUnknownForObjectMarshal.GetIDispatchForObject

我相信你正在寻找Marshal.GetComInterfaceForObject()方法。