My MEX file is written in C++/CLI and calls a DLL written in C#.
When gcnew'ing an object, shouldn't it be garbage collected when the mexFunction returns? Its references should be lost but nothing seems to be garbage collected... each call to the mex function increases MATLAB's memory allocation (and no, the memory is not used for MATLAB variables).
I've experimented with creating a large dummy value with narrow scope and when stepping through the MEX file I can see the memory allocated and released. But not so with the main object created in the mexFunction =(
I've tried to delete it in the destructor and finalizer, but I can't get it to garbage collect. How can I free the managed memory when returning to MATLAB?
I don't think external DLL filers are the problem. To illustrate, I created this silly mexFunction:
public ref class Foo
{
public:
Foo()
{
Dictionary<int,String^>^ bar = gcnew Dictionary<int,String^>;
for(int i=0;i<10000000;i++)
{
bar->Add(i, "abcdefghijklmnopqrstuvxyz");
}
}
};
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[])
{
Foo^ test = gcnew Foo();
}
This bumps MATLAB's memory by around 300 MB, although subsequent calls don't increase the memory further like in my real MEX file.
EDIT:
I answered my own question, the culprit was mxArrayToString