Using mexMakeMemoryPersistent to save C data structures

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

Risposte (1)

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 Commento

Thanks. I am only looking to keep the mod structure intact between calls to the mex function from matlab. I don't need the mod structure inside of matlab (passed from mex to matlab).
So it sounds like I need to use matlab API memory allocation functions inside my top level C function to handle the data structure. Then I also need the mexMakeMemoryPersistent, and mexAtExit functions in my top level C function.

Accedi per commentare.

Categorie

Richiesto:

il 30 Set 2011

Community Treasure Hunt

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

Start Hunting!

Translated by