我使用如下代码计算pdf文件的页数,存在内存泄露;执行pdf保存为word操作时,内存泄露更严重,而且内存不足时,软件会崩溃,请问如何避免内存泄露呢?
int GetPDFPages(const std::wstring& strFilePath, const std::wstring& strPassword)
{
int nPages = 0;
try
{
wchar_t szLog[1024] = { 0 };
swprintf(szLog, L"计算总页数开始(内存大小:%d)\n", GetProcessMemorySize());
OutputDebugString(szLog);
System::String strDocument(strFilePath.c_str(), strFilePath.length());
System::String strDocumentPassword(strPassword.c_str(), strPassword.length());
if (!System::IO::File::Exists(strDocument))
{
return Aspose_FileNotExist;
}
auto doc = System::MakeObject<Aspose::Pdf::Document>(strDocument, strDocumentPassword);
auto Pages = doc->get_Pages();
nPages = Pages->get_Count();
Pages.reset();
doc.reset();
swprintf(szLog, L"计算总页数结束(内存大小:%d)\n", GetProcessMemorySize());
OutputDebugString(szLog);
}
catch (...)
{
return Aspose_PasswordError;
}
return nPages;
}
// 获取内存大小
int GetProcessMemorySize()
{
HANDLE handle = GetCurrentProcess();
::PROCESS_MEMORY_COUNTERS_EX pmc = { 0 };
int a = sizeof(pmc);
if (!::GetProcessMemoryInfo(handle, (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)))
{
DWORD errCode = GetLastError();
return 0;
}
return pmc.WorkingSetSize / 1000000;
}