Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB MEX interface to a class object with multiple functions

Tags:

c++

oop

matlab

mex

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?

like image 954
Paul Avatar asked Jul 25 '09 14:07

Paul


2 Answers

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.

like image 63
Mr Fooz Avatar answered Oct 24 '22 02:10

Mr Fooz


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.

like image 31
Dima Avatar answered Oct 24 '22 03:10

Dima