正确发布OleCreateFromFile

时间:2013-08-14 14:42:48

标签: c# interop ole

首先。谢谢你的任何建议!

我正在开发一个OpenXML项目,我需要将文件转换为* .bin格式。

一切正常,但是当我运行测试app时,我注意到每次调用OleCreateFromFile(..)

时,与应用程序关联的GDI对象的数量都在增加

代码:

        //init stuff
        storage = null;
        pOle = null;
        var result = OLE32.StgCreateStorageEx(oleOutputFileName,
            Convert.ToInt32(OLE32.STGM.STGM_READWRITE | OLE32.STGM.STGM_SHARE_EXCLUSIVE | OLE32.STGM.STGM_CREATE | OLE32.STGM.STGM_TRANSACTED),
            Convert.ToInt32(OLE32.STGFMT.STGFMT_DOCFILE),
            0,
            IntPtr.Zero,
            IntPtr.Zero,
            ref OLE32.IID_IStorage,
            out storage
        );

        if (!HandleResult("StgCreateStorageEx", result))
            return false;

        var CLSID_NULL = Guid.Empty;
        msOleInterop.FORMATETC f = new msOleInterop.FORMATETC();          
        //Creates an embedded object from the contents of a named file. 
        string newInput = MultibyteToUnicodeNETOnly(_inputFileName, 1252);            
        result = OLE32.OleCreateFromFile(
            ref CLSID_NULL,
            newInput,
            ref OLE32.IID_IOleObject,
            (uint)msOleInterop.OLERENDER.OLERENDER_NONE,
            ref f,
            null,
            storage,
            out pOle
        );

......并且以这种方式发布还不够。 GDI对象仍在增加(每个OleCreateFromFile调用大约+2。

//Object release:    
    Marshal.ReleaseComObject(storage);               
    Marshal.ReleaseComObject(pOle); 

OleCreateFromFile的定义

   #region OleCreateFromFile
    [DllImport("ole32.dll")]
    public static extern int OleCreateFromFile([In] ref Guid rclsid,
        [MarshalAs(UnmanagedType.LPWStr)] string lpszFileName,
        [In] ref Guid riid, 
        uint renderopt,
        [In] ref FORMATETC pFormatEtc/*IntPtr pFormatEtc*/,
        IOleClientSite pClientSite, 
        Microsoft.VisualStudio.OLE.Interop.IStorage pStg,
        out Microsoft.VisualStudio.OLE.Interop.IOleObject ppvObj);        
    #endregion           

1 个答案:

答案 0 :(得分:0)

使用

Marshal.FinalReleaseComObject(obj) 

您认为是对com对象的引用