簡體   English   中英

使用 CComBstr 和 system::string 時 Memory 泄漏

[英]Memory leaks while using CComBstr and system::string

class ATL_NO_VTABLE CMasterStore : 

    public CComObjectRootEx<CComSingleThreadModel>,

    public CComCoClass<CMasterStore, &CLSID_MasterStore>,

    public IDispatchImpl<IMasterStore, &IID_IMasterStore, &LIBID_PSLOGLib>
{

STDMETHODIMP CMasterStore::get_Description(BSTR *pVal)
{
   *pVal = fbstrDescription.Copy();
    return S_OK;
}

STDMETHODIMP CMasterStore::put_Description(BSTR newVal)
{

   //SetDirty();

   fbstrDescription = newVal;

    return S_OK;
}
};

/* 下面使用的 masterStore 是此處定義的 c# class

公共參考 class MasterStore { 公共:屬性短代碼; 屬性字符串^ 描述;*/

IMasterStore* _CurrentMasterStore; //界面

下面的代碼行導致 memory 泄漏..

_CurrentMasterStore->put_Description(static_cast<BSTR>(Marshal::StringToBSTR(masterStore->Description).ToPointer()));

如果我只是按如下方式傳遞字符串,我看不到任何 memory 泄漏。

_CurrentMasterRecord->put_Description(L"Test memory leaks");

我無法找到它泄漏的原因以及如何修復它。

任何幫助表示贊賞。

非常感謝您提前!!

StringToBSTR 方法在系統堆上為字符串分配一個 BSTR,並分配將字符串放入新分配的 BSTR 並返回指向該字符串的指針。 Memory 已代調用方分配,調用方負責在不再需要時釋放 memory(大概在調用 put_Description 之后)

第二種方法可能會將字符串作為常量文字放入代碼中,因此不會分配 memory。 BSTR 通常在字符串跨越進程邊界時使用,因為字符串文字不會完整地跨越進程邊界。 此外,BSTR 與寬字符串(L'My string')不同 - 請參閱https://social.msdn.microsoft.com/Forums/vstudio/en-US/75a504d1-03b7-4592-8dab-b6897585de6a/bstr -bstrt-sysallocstring-wchar-and-passing-parameters-to-wmi-methods?forum=vcgeneral

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM