开发者

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

I have Matlab code that ca开发者_JAVA技巧lls a MEX generated from c++ code. The c++ code requires heavy memory allocation and calculations upon initialization. Using a static pointer, initialization is done only on the first call and the pointer is read from on subsequent calls.

Everything worked just fine until this Matlab code was compiled using Matlab Compiler. Now subsequent calls to the MEX (now happening within matlab compiled code) end up crashing because the static pointer apparently references invalid memory.

What can be done to avoid duplicate initialization in this case?

Thanks, Leo


Excellent question. You might have to break this up into two different mex functions, one that computes the initialization and returns its results, and another that does your function.

  [heavyCompResults,otherHeavyResults] = initComputation(initParams);

Then:

  performComputation(compParams,heavyCompResults,otherHeavyResults);

Alternately, you could write things out in a file instead of passing it through Matlab.

  initComputation(initParams,initResultsFname);  %writes initResultsFname

Then:

  performComputation(compParams,initResultsFname); %reads initResultsFname

One more alternative:

Make your code into a DLL and use the loadLibrary function in Matlab. That way, when you create the static it should probably stay in memory between calls. But I haven't verified this.


I'm not sure if you have solved your issue yet or not, but here's some relevant information that helped me.

This seems similar to an issue I was having. When compiling a new version of the same function (where one had memory access issues), I found that the old version of the mex function did not actually leave the memory. I tried a multitude of things, including (supposedly) clearing the mex function from matlab memory using clear mex-file-name. The only successful way to prevent repeated access to the same flawed mex function I found was to restart matlab. This fixed the memory issue every time. While this case and solution don't exactly match your problem, my suggestion is to try restarting matlab. Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜