tags:

views:

667

answers:

2

I am using the MEX interface to run C++ code in MATLAB. I would like to add several functions to MATLAB for handling a System object:

sysInit()
sysRefresh()
sysSetAttribute(name, value)
String = sysGetAttribute(value)
sysExit()

Since each MEX dll can contain one function, I need to find a way to store the pointer to the global System object which will exist until deleted by a call to sysExit.

How can I do this in MATLAB properly? Are there any ways to store global pointers across calls to MEX functions?

+4  A: 

One common approach is to have several m-file functions that provide the public interface, e.g. sysInit.m, sysRefresh.m, etc.

Each of these m-files calls the mex function with some kind of handle, a string (or number) identifying the function to call, and any extra args. For example, sysRefresh.m might look like:

function sysRefresh(handle)
return sysMex(handle, 'refresh')

In your sysMex mex function, you can either have the handle be a raw heap pointer (easy, but not very safe), or you can maintain a mapping in C/C++ from the handle ID to the actual object pointers. This solution requires a little extra work, but it's much safer. This way someone can't accidentally pass an arbitrary number as a handle, which acts as a dangling pointer. Also, you can do fancier things like use an onCleanup function to release all memory and resources when you unload the mex function (e.g. so you don't have to restart matlab when you recompile the mex function).

You can go a bit further if you like and hide the handle behind a Matlab class. Read up on the OO features for Matlab in the docs if you're interested. If you're using a recent version, you can take advantage of their much cleaner handle objects.

Mr Fooz
Thanks Mr. Fooz. I have implemented with handle (directly as the pointer) and it seems to be working.This is a bit surprising for me that the class object allocated in the heap, is not deleted when mex function returns.Is this a normal behavior which I can rely on on Windows (XP, Vista and 7) ?Thanks a lot again.
Paul
If you allocate objects using Matlab's allocator, they are automatically deleted upon returning from the mex function. If you use malloc or new, then Matlab doesn't know about them and thus doesn't de-allocate.
Mr Fooz
+2  A: 

Alternatively, you may get away with not using MEX at all. In matlab (on Windows) you can load any generic dll with loadlibrary and call any of its functions with callib. This is probably not portable across operating systems, though.

Dima
This is also a good hint. I would prefer to use the mex interface as it is the official way to extend MATLAB and I am expecting to integrate tightly with MATLAB.Thank you very much.
Paul

related questions