How to avoid duplicate .mex initialization (compiled Matlab code)?

I have Matlab code that calls MEX generated from C ++ code. C ++ code requires intensive memory allocation and computation during initialization. Using a static pointer, initialization is only performed on the first call, and the pointer is read from subsequent calls.

Everything worked fine until this Matlab code was compiled using the Matlab Compiler. Now subsequent MEX calls (now occurring in the compiled Matlab code) fail, because the static pointer seems to refer to invalid memory.

What can be done to avoid duplication of initialization in this case?

Thanks Leo

+4
source share
2 answers

Great question. You may have to break it down into two different functions: one that calculates the initialization and returns its results, and the other that performs your function.

[heavyCompResults,otherHeavyResults] = initComputation(initParams); 

Then:

  performComputation(compParams,heavyCompResults,otherHeavyResults); 

Alternatively, you can write things in a file rather than passing it through Matlab.

  initComputation(initParams,initResultsFname); %writes initResultsFname 

Then:

  performComputation(compParams,initResultsFname); %reads initResultsFname 

Another alternative:

Make your code in a DLL and use the loadLibrary function in Matlab . Thus, when you create a static file, it should probably remain in memory between calls. But I did not confirm this.

+1
source

I'm not sure if you have solved the problem or not, but here is some relevant information that helped me.

This is similar to the question I had. When compiling a new version of the same function (where you had problems accessing memory), I found that the old version of the mex function does not actually leave memory. I tried many things, including (presumably) clearing the mex function from Matlab memory using the explicit name of the mex file. The only successful way to prevent re-access to the same erroneous mex function that I found is to restart the matlab. This fixed a memory problem every time. Although this case and solution do not exactly match your problem, my suggestion is to try restarting the matlab. Hope this helps.

0
source

All Articles