I have a C++ MFC application which consumes C# COM wrapper. The issue is whenever I invoke a function inside wrapper, I am experiencing memory leak. Can anyone explain how to clean up the allocations that are made within the C# COM wrapper.
Below code blocks mimic what I was trying to do, can anyone provide me the references/rightway to pass the structure object/ clean up the memory allocation
C# wrapper exposed as COM
using System;
using System.Runtime.InteropServices;
namespace ManagedLib
{
[ComVisible(true)]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct comstructure
{
public string[] m_strName;
public UInt32[] m_nEventCategory;
}
[Guid("4BC57FAB-ABB8-4b93-A0BC-2FD3D5312CA8")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[ComVisible(true)]
public interface ITest
{
comstructure TestBool();
}
[Guid("A7A5C4C9-F4DA-4CD3-8D01-F7F42512ED04")]
[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
public class Test : ITest
{
public comstructure TestBool( )
{
comstructure testvar = new comstructure();
testvar.m_strName = new string[100000];
testvar.m_nEventCategory = new UInt32[100000];
return testvar;
}
}
}
C++ code
#include <iostream>
#include <afx.h>
#include <afxwin.h>
#include <afxext.h>
#include <afxdtctl.h>
#include "windows.h"
#include "psapi.h"
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>
#endif // _AFX_NO_AFXCMN_SUPPORT
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
#include <atlbase.h>
#import "..\comlibrary\bin\Debug\comlibrary.tlb"
comlibrary::ITest* obj;
class mleak
{
public:
void leakmemory()
{
comlibrary::comstructure v2;
v2 = obj->TestBool();
}
};
int main()
{
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
CLSID clsid;
HRESULT hResult = ::CLSIDFromProgID(L"ManagedLib.Test", &clsid);
hResult = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
__uuidof(comlibrary::ITest), (void**)&obj);
std::cout << hResult;
if (FAILED(hResult))
{
std::cout << "COM import failed!\n";
}
mleak m1;
for (int i = 0; i < 600; i++)
{
m1.leakmemory();
Sleep(100);
}
return 0;
}
m1.leakmemory();memory holding up by my process is linearly increasing with the for loop @IInspectableTestBoolreturns a object, I would expect that object needs to be manually disposed somehow. I'm no COM expert, but com objects are typically reference counted, so I would expect there to be aRelease()method on the comstructure to decrease the refcount.