7

I'm about to write a Mex File, so I can use my c++ code in MATLAB.

This code is built around a singleton class (in c++).

I've read that for memory to be persistent I have to use MxAlloc isntead of malloc/new, is this true for all memory I use? I.e, the class I have uses vectors, and vectors automatically allocate new memory, using standard mechanisms.

So will a vector in a class allocated using MxAlloc have trouble keeping it's memory?

Andreas Mieritz
  • 135
  • 2
  • 6
  • Great question - this issue is not very well explained in the documentation. I've heard of people needlessly re-writing entire libraries thinking they need to change each memory call to make it MEX-compatible. – Bill Cheatham Mar 27 '12 at 08:45
  • Thank you! The rewriting is exactly what I wanted to avoid since the library is still being developed and it would result in me having 2 instances of the library, one for c/c++ work and one for MATLAB prototyping. – Andreas Mieritz Mar 27 '12 at 09:04
  • Bear in mind though, that there are further subtleties I am not entirely sure of. For example, if the Mex file is interrupted (e.g. through an error), memory allocated via standard C methods *may* not be properly deallocated... further input on this point from people in the know would be appreciated! – Bill Cheatham Mar 27 '12 at 09:21

1 Answers1

7

You only use MxAlloc for the data that you are going to return to Matlab. Everything that stays within your library can be allocated normally.

One issue you may want to be aware of is that your library can be unloaded at any time. Normally when the user calls your mexFunction the library is loaded and will stay loaded for subsequent calls. However, at anytime Matlab may unload your library and so all the resources in your mexFunction will be freed.

Dusty Campbell
  • 3,146
  • 31
  • 34
  • 3
    If necessary, you can use mexLock http://www.mathworks.co.uk/help/techdoc/apiref/mexlock.html to stop your mex file from being unloaded. – Edric Mar 27 '12 at 08:37