Info

此问题已关闭。 请重新打开它进行编辑或回答。

Prevent MEX Memory Persistence

1 次查看(过去 30 天)
Andrew
Andrew 2014-9-10
关闭: MATLAB Answer Bot 2021-8-20
Is there a way to prevent the values of class properties of a MEX from persisting? I understand there are functions to cause memory to persist (i.e. "mexMakeMemoryPersistent"); but I don't see a function like "mex_DONT_MakeMemoryPersistent".
For instance, if I have:
SomeClass.h
. . . . . . . . . . . . . . . .
class CSomeClass {
public: CSomeClass(); ~CSomeClass();
int iVariable;
};
vars.cpp . . . . . . . . . . . . . . . .
#include "SomeClass.h"
CSomeClass oSC;
mains.cpp . . . . . . . . . . . . . . . . #include "SomeClass.h"
extern CSomeClass oSC;
void mexFunction(itype nlhs, mxArray *plhs[], itype nrhs, const mxArray *prhs[]) {
//This will print 0 the 1st time
//This will print 100 the 2nd time
mexPrintf("oSC.iVariable = %d\n", oSC.iVariable);
oSC.iVariable = 100;
}
Now within Matlab:
>>mex mains.cpp SomeClass.cpp
>>mains
oSC.iVariable = 0
>>mains
oSC.iVariable = 100
//This is to demonstrate that the value of oSC.iVariable persisted between MEX calls

回答(1 个)

Geoff Hayes
Geoff Hayes 2014-9-12
Andrew - the way I understand how MEX works (and I could be off) is that by calling the MEX function, you are loading it into memory, and it will remain there until you clear the function or terminate your MATLAB session. You can see this "loaded" function using the inmem function. After calling mains the first time, type the following code in the Command Window
[loadedFncs,loadedMexFncs] = inmem('-completenames');
loadedMexFncs
loadedMexFncs =
'/Applications/MATLAB_R2014a.app/toolbox/matlab/graph2d/private/lineseriesmex.mexmaci64'
'/Users/geoff/Development/matlab/testing/mains.mexmaci64'
So the function is in memory, as is the instance of the CSomeClass class. And when you call mains again, you observe that the iVariable is now 100.
If you want to clear the persistent variable between calls to mains, then you could just clear the function in between the two calls
>> mains
oSC.iVariable = 0
>> clear mains
>> mains
oSC.iVariable = 0
Or you could create your instance of CSomeClass in another manner (for example, as a local variable with the mains function) so that it will not persist between calls to mains.

此问题已关闭。

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by