2011-02-23 52 views
4

我試圖執行此功能:如何獲取指向接口的指針?

public static int QueryInterface(
    IntPtr pUnk, 
    ref Guid iid, 
    out IntPtr ppv 
) 

其中

pUnk 
Type: System.IntPtr 
The interface to be queried. 

基本上,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); 

回答

4

閱讀Marshal.QueryInterface()頁面上的備註部分的最後一行。

QueryInterface方法公開了一個COM對象的IUnknown::QueryInterface方法,該方法嘗試獲取特定的接口指針。 [...]要獲得表示IUnknown接口指針的IntPtr值,可以撥打Marshal.GetComInterfaceForObject,Marshal.GetIUnknownForObjectMarshal.GetIDispatchForObject

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

+0

謝謝。我會研究這一點。 – 2011-02-23 08:15:41