From: Anthony Halley on
Hello Oliver,

Did you ever find a nice solution for this issue? If so, I'd be interested in hearing about it.

Thanks,
Anthony
From: Oliver Woodford on
"Anthony Halley" wrote:
> Did you ever find a nice solution for this issue? If so, I'd be interested in hearing about it.

Yes. Walter Roberson pointed out the properties of the handle class to me, including it's ability to call a clean up function, here:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/283309

So the solution is to define a class which inherits the handle class, something like this:

classdef myclass < handle
properties (Hidden = true, SetAccess = private)
cpp_handle;
end
methods
% Constructor
function this = myclass()
this.cpp_handle = init_mex();
end
% Destructor
function delete(this)
clear_mex(this.cpp_handle);
end
% Example method
function output = action(this, data)
output = action_mex(this.cpp_handle, data);
end
end
end

I was going to post this when I'd used and tested it, but your question prompted me to post it earlier. As a result, it may not be exactly right, but hopefully you get the gist.

Oliver
From: Oliver Woodford on
"Oliver Woodford" wrote:
> Walter Roberson pointed out the properties of the handle class to me.

Oops. It wasn't Walter, but Steve Lord! Sorry, Steve.
From: Walter Roberson on
Oliver Woodford wrote:
> "Oliver Woodford" wrote:
>> Walter Roberson pointed out the properties of the handle class to me.
>
> Oops. It wasn't Walter, but Steve Lord! Sorry, Steve.

You did have me wondering...
From: Anthony Halley on

> So the solution is to define a class which inherits the handle class, something like this:
>
> classdef myclass < handle
> properties (Hidden = true, SetAccess = private)
> cpp_handle;
> end
> methods
> % Constructor
> function this = myclass()
> this.cpp_handle = init_mex();
> end
> % Destructor
> function delete(this)
> clear_mex(this.cpp_handle);
> end
> % Example method
> function output = action(this, data)
> output = action_mex(this.cpp_handle, data);
> end
> end
> end
>

Thank you Oliver. Couple more questions:

What exactly are you returning from init_mex()? Is that a pointer to a C++ class instance? Are you using "new" or "mxMalloc" to allocate the memory for that instance?