我如何使用Marshal.QueryInterface?

时间:2011-02-22 10:54:33

标签: c#

我正在尝试使用Word文档中的一些嵌入对象。早先的一张海报告诉我,这不是直截了当的。以下是相关答案的摘录:

  

“正如我之前提到的,利用   嵌入式对象的编程模型   执行保存是一个   捷径。有更多参与   解决方案将适用于任何   嵌入式对象。为了   要嵌入第一个对象   这个地方,必须支持其中一个COM   IPersist接口(即   IPersistStorage,IPersistStreamInit,   IPersistFile等)。因此,一个   嵌入对象总是可以的   通过调用提取   Marshal.QueryInterface上   OLEFormat.Object(确定   适当的持久性接口),   相应地投射然后打电话   适当的方法。取决于   您使用哪个持久性接口,   你可能需要再打个电话   暴露适当的方法   存储在文件顶部。也,   取决于嵌入的类型   对象,您可能仍需要激活   在能够之前的对象   成功的QueryInterface   持久性接口。“

所以我有兴趣公开对象正在实现的接口。我能找到的最近的是here。到目前为止的代码如下所示,非常感谢Marshal.QueryInterface的任何帮助。

// Opening the word document
object missing = Type.Missing;
this.document = wordApp.Documents.Open(
                ref fn, ref confirmConversions, ref readOnly, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing);

foreach (Microsoft.Office.Interop.Word.InlineShape inlineShape in this.document.InlineShapes)
            {
                if (inlineShape.OLEFormat.ProgID != null)
                {
                    switch (inlineShape.OLEFormat.ProgID)
                    {
                        // This is a pdf file
                        case "AcroExch.Document.7":
                            //Marshal.QueryInterface(IntPtr pUnk, ref Guid iid, out IntPtr ppv);
                            break;
                        default:
                            break;
                    }
                }
            }

2 个答案:

答案 0 :(得分:4)

Marshal.QueryInterface不是必需的 - 如果您使用COM对象并将其转换为COM接口类型,.NET会为您执行QueryInterface调用。也就是说,你可以写:IPersistStorage persist = (IPersistStorage) obj;

但是我不清楚代码中的哪个对象实现IPersistStorageIPersistStreamInit等。

答案 1 :(得分:2)

我不确定你打算做什么,但可以调用QueryInterface。唯一的问题是,您在这里有一个ProgID,您需要先从CLSID获取[DllImport("ole32.dll")] static extern int CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid pclsid); 。您可以通过pInvoking CLSIDFromProgId函数来完成。

Marshal.QueryInterface(IntPtr.Zero, CLSIDFromProgID(progID), out pInterface);

然后,你可以这样称呼:

{{1}}
相关问题