Using mexMakeMemoryPersistent to save C data structures
Show older comments
I am using a mex function (mymodel) to run a C simulation model. I use mex inputs and outputs to specify input/output waveforms and parameters. One of the C blocks (model_init) sets up data structures such as mod->gain1, mod->gain2, etc. Some of the entries are mod->gain3.in, mod->gain3.out, etc. The pointer to these structures is then passed to the next C block (model_run) which runs the waveform through the model using the mod data structure.
Now when I exit mymodel and then later want to run mymodel, I don't want to have to re-iniialize the mod data structure. I want to be able to call model_run with it seeing the mod data structure.
1. How do I pass a data structure such as mod->gain1 from C to mex? Can I use any of the mxGet.. functions? The structure is not an array or a number or a string. 2. How do I use mexMakeMemoryPersistent on the data structure? Thanks
Answers (1)
James Tursa
on 1 Oct 2011
0 votes
mexMakeMemoryPersistent only works for MATLAB API allocated memory using mxMalloc, mxCalloc, and mxRealloc. It will not work with native C allocated memory using malloc, calloc, or realloc. So the first step in your process is to make sure all of the memory behind your mod structure pointer is allocated from MATLAB API functions. Then you can use mexMakeMemoryPersistent on the allocated pieces. HOWEVER, this will place the burden of freeing this memory on you since you have basically told MATLAB to not garbage collect it. So you will need some type of functionality in a mexAtExit function to clean up the persistent allocated memory when the mex function get cleared. You will also need to have the mod pointer itself persistent from call to call, e.g. make it a top level (global) variable. All of this works for data that remains in the mex function. If you want the data to pass back & forth between the mex function and the MATLAB workspace then you have a bigger job ahead of you. Is that what you are after?
1 Comment
Bob Elsheimer
on 3 Oct 2011
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!