MATLAB: Using Mex with Classes

cclassMATLABmex

I have written a mex file to 1. Initialize hardware. 2. Get Data. 3. Close & Exit hardware.
—-Some_App.cpp—-
void mexFunction(parms)
{
handle = init_hw();
alloc_mem(handle);
get_data();
copy_to_mxDoubleMatrix();
exit_hw(handle);
}
This works fine.
I have to change it such a way that init_hw(); is in a different class. Using this handle, I need to be able to allocate_mem(handle), get_data()… say a 100 times, then exit_hw(handle); as the init_hw() takes long to run I don't want to init_hw() everytime.
Can I do something to separate them into classes and use like
handle = Some_App.init_hw();
for i = 1:100
array = Some_App.acquire(handle); /*All Memalloc, read go into this class*/
end
Some_App.exit_hw(handle);
Any Tutorials/Help/Links can be useful. Thanks

Best Answer

One option is to keep your pointer in a high level variable (i.e., global) and set up a mexAtExit function to clean things up when the function is cleared. E.g.,
void *handle = NULL; // not sure of type here ... you didn't declare it above
void clear_handle(void)
{
if( handle ) {
exit_hw(handle);
handle = NULL;
}
}
void mexFunction( ...parms... )
{
if( !handle ) {
handle = init_hw();
if( !handle ) {
mexErrMsgTxt("Unable to init handle.");
}
mexAtExit(clear_handle);
}
alloc_mem(handle);
get_data();
copy_to_mxDoubleMatrix();
}
Only on the first call init_hw is called and the handle remembered. When you clear this routine from memory, exit_hw is called to clean things up.