mxMalloc vs mxCreate
5 views (last 30 days)
Show older comments
When talking to compiled Matlab code (not writing a mex file), is there any reason I would ever use mxMalloc or mxCalloc()? Am I correct that this is only for mex environments where my C code is running within the Matlab process and I want to allocate on the Matlab heap? And anything I need to create to pass to compiled Matlab I can do with mxCreate*?
If I need to call mxSetPr when talking to compiled Matlab code, can I give it a pointer allocated on the C heap, or does that also need to be allocated on the Matlab heap? Will bad things happen if I call mxDestroy on an mxArray after calling mxSetPr and providing a C-allocated array?
Thanks!
-Dan
0 Comments
Answers (2)
James Tursa
on 17 Aug 2011
You will need to provide more details on your questions. For your 2nd paragraph, note that you CANNOT mix C native memory into an mxArray unless you are VERY, VERY, CAREFUL to not call mxDestroyArray on it. To do so would probably cause a MATLAB crash. You would have to manually detach the C allocated memory from the mxArray (and NULL out the associated pointers in the mxArray) before calling mxDestroyArray on it. Under no circumstances should a mixed-memory-model mxArray be passed back into the MATLAB workspace. As long as the mxArray is valid, you can use mxGetPr etc on it regardless of where the memory came from.
0 Comments
Daniel
on 17 Aug 2011
1 Comment
James Tursa
on 17 Aug 2011
You are probably OK as long as you are careful. E.g., create an empty mxArray, then attach C native memory (or C allocated heap memory) to the mxArray via mxSetPr, then call your MATLAB function with this mixed mxArray as one of the inputs, then use mxSetPr to NULL out the pointer in the mxArray, then call mxDestroyArray on the mxArray. So the MATLAB memory manager never tries to free the C native memory. I am assuming that your compiled MATLAB function doesn't do anything with the input that would cause it to be a shared data copy (e.g., copied into a global variable). That would cause trouble.
See Also
Categories
Find more on MATLAB Compiler 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!