Posted by a ceTe Software moderator
Hello,
Below is the code that shows how to create and release DynamicPDF objects (including image objects) correctly to avoid memory leaks.
::CoInitialize(NULL);
for(int i = 0; i<25; i++)
{
Sleep(3000);
CComPtr<DynamicPDF::IDocument> objDoc;
CComPtr<DynamicPDF::IPage> objPage;
CComPtr<DynamicPDF::IImage> objImage1;
CComPtr<DynamicPDF::IImage> objImage2;
CComPtr<DynamicPDF::IImage> objImage3;
VARIANT varImage;
HRESULT hr=::CoCreateInstance(CLSID_Document,NULL,CLSCTX_INPROC_SERVER,IID_IDocument,(void**)&objDoc);
if(hr != S_OK)
return 0;
objDoc->AddPage(&objPage);
if(objPage== NULL)
goto Cleanup;
WCHAR lpCurDir[512];
WCHAR lpFilePath[512];
::GetCurrentDirectoryW(512,lpCurDir);
wsprintf(lpFilePath,L"GeneratedOutput_%d.pdf",i);
VariantInit(&varImage);
varImage.vt = VT_BSTR;
varImage.bstrVal = SysAllocString(TEXT("DPDFlogo.png"));
objPage->AddImage(varImage, 0, 200, 100, &objImage1);
VariantClear(&varImage);
VariantInit(&varImage);
varImage.vt = VT_BSTR;
varImage.bstrVal = SysAllocString(TEXT("DPDFlogo2.png"));
objPage->AddImage(varImage, 0, 200, 100, &objImage2);
VariantClear(&varImage);
VariantInit(&varImage);
varImage.vt = VT_BSTR;
varImage.bstrVal = SysAllocString(TEXT("DPDFlogo3.png"));
objPage->AddImage(varImage, 0, 200, 100, &objImage3);
VariantClear(&varImage);
BSTR FilePath= SysAllocString(lpFilePath);
hr = objDoc->DrawToFile(FilePath);
if(hr != S_OK)
goto Cleanup;
Cleanup:
if(objImage1 != NULL)
{
objImage1.Release();
objImage1 = NULL;
}
if(objImage2 != NULL)
{
objImage2.Release();
objImage2 = NULL;
}
if(objImage3 != NULL)
{
objImage3.Release();
objImage3 = NULL;
}
if(FilePath!= NULL)
{
SysFreeString(FilePath);
FilePath = NULL;
}
if(objPage != NULL)
{
objPage.Release();
objPage = NULL;
}
if(objDoc!= NULL)
{
objDoc.Release();
objDoc = NULL;
}
}
::CoUninitialize();
Thanks,
ceTe Software Support Team.