Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Making C++ objects persistent between mex calls, and robust.

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 1 Apr, 2010 15:23:09

Message: 1 of 39

Hi all

I'd like to revisit the question of how to make C++ objects persist between mex calls safely. This topic has been discussed before in the following thread:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/156994
(and many others), without a perfect solution (IMO).

The aim is this: given a C++ object created in a mex file, to pass this object or a reference to this object (ensuring the object persists in memory) back to Matlab, such that this object can be used again in future calls to a mex function (not necessarily the same one). It should also be robust to memory leaks - e.g. an error in Matlab should not cause any memory to become irretrievable.

Several solutions have been proposed (or if not, I propose them now), and I want to address the problems with each of these:

1. Make the object static:
Problems - Firstly, if the mex file is cleared from memory for any reason then the object's state is lost. A call to mexLock can stop this, but then you need to create functionality to reset the object or unlock the function. Secondly, you can only use one object at a time, and cannot share it across mex files. However, there can be times when we want to instantiate two objects of a given class at the same time. A solution could be to statically allocate a pool of objects, but this wastes memory and doesn't get round the first problem. Lastly, if an error occurs in Matlab then the object needs to be reset manually by the user (e.g. by clearing the mex function).

2. Wrap your entire algorithm in a C++ function, and use mexCallMatlab to call the Matlab functions you want:
My main issues with this are that it is cumbersome to set up, and it makes the solution much less portable. It may also make the algorithm difficult to interrupt (or will cause memory leaks) and to profile.

3. Allocate the object's memory (if using mxMalloc, use mexMakeMemoryPersistent to make the object persist in memory), and pass back a pointer (as a uint32) to Matlab. The code at:
http://www.ee.columbia.edu/~mim/meap/paMat/mexhandle/
does this, adding in some nice type checking for robustness, but doesn't use mxMalloc so can potentially cause memory leaks. Using mxMalloc can still potentially cause memory leaks if you don't set up an exit callback function using mexAtExit, but then you have the same problem as with a static object/pointer, that the object will disappear if the mex function is cleared from memory. Even then, if you get an error you need to then clear the mex function to make sure any objects left hanging around are mopped up.

4. Allocate the object's memory using mxMalloc, and return this entire array to Matlab as a uint8 vector.
This solves the problem of (some) memory leaks. You can keep and reuse the object even when the mex function is cleared, and simply delete the array when you're done with the object. If an error occurs then Matlab will delete the object for you. However, there is one further consideration. If a C++ object has allocated further memory, then this memory should be freed when the object is destroyed, and this is handled by the object's destructor function. This destructor function therefore needs to be called when the object is destroyed.

To summarise, all but solution 1 can lead to memory leaks if there is an error in Matlab, and solution 1 limits you to a specific number of objects which do not persist if the mex function is cleared, does not allow objects to be shared between mex files, and requires the mex function to be cleared from memory following an error in Matlab (to reset the object). It would be nice to have a solution that just works.

So, finally, some questions: Is is possible to create a Matlab class around a C++ object, which knows how to destroy the object properly when it is cleared in Matlab? How backwards compatible can such a solution be made?

Thanks,
Oliver

Subject: Making C++ objects persistent between mex calls, and robust.

From: Anthony Halley

Date: 7 Jun, 2010 21:21:05

Message: 2 of 39

Hello Oliver,

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

Thanks,
Anthony

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 8 Jun, 2010 09:19:04

Message: 3 of 39

"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

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 8 Jun, 2010 09:28:03

Message: 4 of 39

"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.

Subject: Making C++ objects persistent between mex calls, and robust.

From: Walter Roberson

Date: 8 Jun, 2010 12:31:02

Message: 5 of 39

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...

Subject: Making C++ objects persistent between mex calls, and robust.

From: Anthony Halley

Date: 8 Jun, 2010 13:34:06

Message: 6 of 39


> 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?

Subject: Making C++ objects persistent between mex calls, and robust.

From: Anthony Halley

Date: 8 Jun, 2010 13:42:05

Message: 7 of 39


> 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. I have a couple more questions if you have a second:

What are you returning from init_mex()? Is that a pointer to a C++ class instance? If so, how are you allocating the memory, are you using "new" or "mxMalloc"?

Subject: Making C++ objects persistent between mex calls, and robust.

From: Anthony Halley

Date: 8 Jun, 2010 13:47:04

Message: 8 of 39

Please excuse the double-post, sorry about that.

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 8 Jun, 2010 14:41:04

Message: 9 of 39

"Anthony Halley" wrote:
> 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?

I haven't gotten round to implementing it myself, but I plan to return a pointer to a C++ class instance (cast as a uint64), with memory allocated using "new". MATLAB will call the myclass delete function when it clears the pointer, so the only time this wouldn't happen is if MATLAB crashed. However, in that case I'd hope that the OS' memory management system would free all the memory associated with that thread, including the memory allocated by "new".

Subject: Making C++ objects persistent between mex calls, and robust.

From: newuser asdf

Date: 22 Jan, 2011 20:55:03

Message: 10 of 39

Hello,

I have some problems in understanding, how this way of object address passing works in my concrete example... Perhaps someone can give me a hint, what I'm doing wrong?

My task: I'm trying to create an instance of a C++ object in a mex file, which then should return its memory address, and another mex function (called afterwards) gets this address as a parameter and calls some functions on it.

I tried to do this in the following way:
I call a mex function, similar to this:
ptr = createObject(.....);

Inside this mex file (createObject) I'm instanciating the object and (trying to) return it:
...
MyObject *obj = new MyObject();
uint64_t ptr = (uint64_t)(obj);
plhs[0]=mxCreateDoublematrix(1,1,mxREAL);
double *resultPtr = mxGetPr(plhs[0]);
*(resultPtr) = ptr;

Then, again in Matlab, I call another mex function, passing this pointer in a structure:
param.ptr = ptr;
doSomething(param);

And in this mex file, I'm trying to get this object, and do something with it:
const mxArray *in = prhs[0];
mxArray *content = mxGetField(in, 0, "ptr");
double *numPtr = mxGetPr(content);
uint64_t ptr = (uint64_t)(*(numPtr));
MyObject *obj = reinterpret_cast<MyObject*>(ptr);
obj->doSomething();

The problem: In this last line, I get an error, and Matlab crashes (probably you might already know the reason?). I've tested the code, deleting the last line (where I "use" the object), and it worked.
I know that with this code I would have a memory leak, but I (would) delete the object later on, through another mex function call... So this is not the problem...

But where is my "big" mistake?
I'm using "new" - so I'm assuming that the object would be persistent; Or do I have to do anything else to assure that (if so, what)?
Or is the fact, that I'm converting the uint64 value to a double (when returning it) a problem?

Can someone give me any suggestion how I can solve this problem, please?

Thanks,
regards,
sabine

Subject: Making C++ objects persistent between mex calls, and robust.

From: Bruno Luong

Date: 22 Jan, 2011 21:42:04

Message: 11 of 39

"newuser asdf" wrote in message <ihfg77$hdg$1@fred.mathworks.com>...

>
> Can someone give me any suggestion how I can solve this problem, please?

For the first look, it smells very fishy they way you convert pointer value (64 bit int) to double back and forth. Are you sure it works (the pointer is not altered when arrived in the second Mex)?

Bruno

Subject: Making C++ objects persistent between mex calls, and robust.

From: Rune Allnor

Date: 23 Jan, 2011 07:55:19

Message: 12 of 39

On Jan 22, 9:55 pm, "newuser asdf" <sabine.schnei...@rolmail.net>
wrote:
> Hello,
>
> I have some problems in understanding, how this way of object address passing works in my concrete example... Perhaps someone can give me a hint, what I'm doing wrong?
>
> My task: I'm trying to create an instance of a C++ object in a mex file, which then should return its memory address, and another mex function (called afterwards) gets this address as a parameter and calls some functions on it.

Don't do that.

You are traversing at least two more layers of software
interference than you would normally care about:

Your C++ function interacts with the OS to translate the
pointer to a physical address in the RAM chips on the
memory rack inside your computer. You usually don't care
about this - the C++ compiler hides all the dirty details
from the programmer.

When you return back to matlab, you enter a world where
Java is a dominant player. As I understand it, the
matlab user interface (where you access the workspaces etc)
are programmed in Java, in which case the Java interpterer
starts messing things up. And the Java interpterer, too,
interacts with the OS. Not necessarily in exactly the same
way that the C++ compiler does, though.

So in order to get back to the physical address where your
C++ object resides, you need to *ensure* that whatever you
do is robust with respect to the interaction of *both* the
Java interpreter *and* the OS.

*Ensuring* that all this works is by no means easy if the
system design is not intended for these kinds of things.
Which matlab isn't.

Find a different way to achieve what you want.

Rune

Subject: Making C++ objects persistent between mex calls, and robust.

From: Bruno Luong

Date: 23 Jan, 2011 08:29:04

Message: 13 of 39

Rune Allnor <allnor@tele.ntnu.no> wrote in message <b3aa9d92-2fe9-4788-a3c0-46ff3e6d6bca@k42g2000yqa.googlegroups.com>...

>
> When you return back to matlab, you enter a world where
> Java is a dominant player. As I understand it, the
> matlab user interface (where you access the workspaces etc)
> are programmed in Java, in which case the Java interpterer
> starts messing things up. And the Java interpterer, too,
> interacts with the OS. Not necessarily in exactly the same
> way that the C++ compiler does, though.

NO, Matlab uses Java engine for graphical purpose only, it does not interact with data, code, internal storing, ... so it does not mess in anyway user data as you assume. Transfer pointers and persistent variable work just fine.

Bruno

Subject: Making C++ objects persistent between mex calls, and robust.

From: newuser asdf

Date: 23 Jan, 2011 09:49:04

Message: 14 of 39

"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <ihgosg$914$1@fred.mathworks.com>...
> Rune Allnor <allnor@tele.ntnu.no> wrote in message <b3aa9d92-2fe9-4788-a3c0-46ff3e6d6bca@k42g2000yqa.googlegroups.com>...
>
> >
> > When you return back to matlab, you enter a world where
> > Java is a dominant player. As I understand it, the
> > matlab user interface (where you access the workspaces etc)
> > are programmed in Java, in which case the Java interpterer
> > starts messing things up. And the Java interpterer, too,
> > interacts with the OS. Not necessarily in exactly the same
> > way that the C++ compiler does, though.
>
> NO, Matlab uses Java engine for graphical purpose only, it does not interact with data, code, internal storing, ... so it does not mess in anyway user data as you assume. Transfer pointers and persistent variable work just fine.
>
> Bruno

Thanks for your help - it works now (without Integer->Double->Integer conversions).
I know that the way I do all this (creating C++ memory leaks, that have to be cleaned up using Matlab...) is not very "clean" programming. But at least it works...

sabine

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 24 Jan, 2011 10:08:03

Message: 15 of 39

"newuser asdf" wrote:
> Iit works now (without Integer->Double->Integer conversions).
> I know that the way I do all this (creating C++ memory leaks, that have to be cleaned up using Matlab...) is not very "clean" programming. But at least it works...

Good. It's worth noting that you are not creating C++ memory leaks; you are simply ensuring that MATLAB doesn't cause memory leaks if you accidentally clear a C++ object without first freeing the memory, by automatically freeing the memory when the object is cleared. There is nothing "unclean" about this; quite the opposite.

I posted the code for the MATLAB class side of things earlier. I'm now posting my code for the C++ side of things below. It includes error checking to make sure you don't convert any uint64 to a pointer, only the true C++ class pointers.

Hope it's useful.
Oliver

// Define types
#ifdef _MSC_VER
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif

#define CLASS_HANDLE_SIGNATURE 0xa5a50f0f
template<class base> class class_handle: public base
{
    public:
        class_handle() : base() { signature = CLASS_HANDLE_SIGNATURE; }
        ~class_handle() { signature = 0; }
        bool isValid() { return (signature == CLASS_HANDLE_SIGNATURE); }
    
    private:
        uint32_t signature;
};

template<class base> inline mxArray *convertPtr2Mat(class_handle<base> *ptr)
{
    mxArray *out = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
    *((uint64_t *)mxGetData(out)) = reinterpret_cast<uint64_t>(ptr);
    return out;
}

template<class base> inline class_handle<base> *convertMat2Ptr(const mxArray *in)
{
    if (mxGetNumberOfElements(in) != 1 || mxGetClassID(in) != mxUINT64_CLASS || mxIsComplex(in))
        mexErrMsgTxt("Input must be a real uint64 scalar.");
    class_handle<base> *ptr = reinterpret_cast<class_handle<base> *>(*((uint64_t *)mxGetData(in)));
    if (!ptr->isValid())
        mexErrMsgTxt("Handle not valid.");
    return ptr;
}

// Code for init_mex() - ISM3D is my C++ object class, but you use your own
class_handle<ISM3D> *ism = new class_handle<ISM3D>;

// Code for clear_mex()
class_handle<ISM3D> *ism = convertMat2Ptr<ISM3D>(prhs[0]);
delete ism;

// Code for action_mex
class_handle<ISM3D> *ism = convertMat2Ptr<ISM3D>(prhs[0]);
ism->action();

Subject: Making C++ objects persistent between mex calls, and robust.

From: Pierre

Date: 3 Feb, 2011 16:12:07

Message: 16 of 39

As this thread seems to be the only thread around, coping with this issue in a serious and advanced manner, and without being choked by contributors not getting the thread's matter, I'd like to point out some further hints regarding this–IMHO very serious–flaw of Matlab.

First, except for the initializing method, one does not necessarily have to write the proxy method WrapperClass/<action> in order to invoke the <action>_mex functions: only declare the <action> method in the class definition and place the mex files in the @WrapperClass directory immediately... you have to implement mexFunction() anyhow, which is another proxy function already and which can take over the part of fetching the C++ object pointer from the Matlab object with mxGetProperty(). I admit, this concerns exclusively code aesthetics but it might slightly improve code maintainability and oversight.

Second, I just started to follow another route for tackling this problem: Java-Interfaces of native objects, which allow you to wrap C++ classes with Java-Interfaces. Latter can instantly be instantiated in Matlab. Unfortunately I haven't had the time to check how transparent type interoperability between both environment-transitions can be realized. Has anybody had some experiences with this approach so far?

Perhaps somewhat off-topic, but still related to the context of my first point, I'd like to ask if anybody has figured out what exactly happens to Matlab objects derived from handle-class when they are being passed to mex-functions? I mean, value-classes get deep-copied at environment-transitions, just as at conventional function-/method-transitions, but what happens exactly to handle-objects, do one has to deep-duplicate it on mex-level to return object changes and then deep-copy back the fields and properties of the duplicate to the original object to preserve behaviour of handle-objects?

Thanks for your points of views, ideas and thoughts.

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 3 Feb, 2011 16:53:03

Message: 17 of 39

"Pierre" wrote:
> First, except for the initializing method, one does not necessarily have to write the proxy method WrapperClass/<action> in order to invoke the <action>_mex functions: only declare the <action> method in the class definition and place the mex files in the @WrapperClass directory immediately... you have to implement mexFunction() anyhow, which is another proxy function already and which can take over the part of fetching the C++ object pointer from the Matlab object with mxGetProperty(). I admit, this concerns exclusively code aesthetics but it might slightly improve code maintainability and oversight.

Another point, which works in favour of the WrapperClass/<action> approach, is that with that approach you can get away with just one mex function. You can then call it with a parameter, e.g. a string, to denote which class function you want to call. That's the way I'm currently doing things, but it is entirely aesthetic, you're right.

Oliver

Subject: Making C++ objects persistent between mex calls, and robust.

From: Pierre

Date: 3 Feb, 2011 17:49:04

Message: 18 of 39

"Oliver Woodford" wrote in message <iiemhf$pev$1@fred.mathworks.com>...
> "Pierre" wrote:
> > First, except for the initializing method, one does not necessarily have to write the proxy method WrapperClass/<action> in order to invoke the <action>_mex functions: only declare the <action> method in the class definition and place the mex files in the @WrapperClass directory immediately... you have to implement mexFunction() anyhow, which is another proxy function already and which can take over the part of fetching the C++ object pointer from the Matlab object with mxGetProperty(). I admit, this concerns exclusively code aesthetics but it might slightly improve code maintainability and oversight.
>
> Another point, which works in favour of the WrapperClass/<action> approach, is that with that approach you can get away with just one mex function. You can then call it with a parameter, e.g. a string, to denote which class function you want to call. That's the way I'm currently doing things, but it is entirely aesthetic, you're right.
>
> Oliver

You are absolutely right Oliver, I hadn't thought about that approach at all. The single-mex approach is probably the most reasonable one for supposedly 99% of the cases one may want to use the technique proposed herein. Being too much focused on my case, I didn't consider that approach as we've got so much handling of parameter-conversion at transition points, that this single mex would easily bloat up to far over 1500 lines of string comparing if statements, type-casting and array copying (comments excluded) which would be hard to maintain (neither in terms of difficulty nor complexity, but I guess it would become quite error-prone over time).

(Meanwhile I also managed to figure out how to alter properties of handle objects immediately from a mex file: Invoking mxSetProperty() on a const_cast of the concerned prhs[i] seems to work just fine. ;) )

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 3 Feb, 2011 18:22:05

Message: 19 of 39

"Pierre" wrote:
> I also managed to figure out how to alter properties of handle objects immediately from a mex file: Invoking mxSetProperty() on a const_cast of the concerned prhs[i] seems to work just fine.

I'd love to hear why you need to do that. It sounds interesting!

Subject: Making C++ objects persistent between mex calls, and robust.

From: Pierre

Date: 15 Feb, 2011 12:52:04

Message: 20 of 39

"Oliver Woodford" wrote in message <iierod$9kp$1@fred.mathworks.com>...
> "Pierre" wrote:
> > I also managed to figure out how to alter properties of handle objects immediately from a mex file: Invoking mxSetProperty() on a const_cast of the concerned prhs[i] seems to work just fine.
>
> I'd love to hear why you need to do that. It sounds interesting!

Let's say I'm a little design-fanatic and always try to get the most out of languages in order to keep code and solutions elegant at a maximum... and this simply includes altering handle objects as handle objects are supposed to behave from mex code too. (There's a doubt whether the effort of searching clean solutions to similar problems would ever pay off compared to simply using the first workaround which comes to one's head, but it's a question of personal honour regarding code quality. ;) )

Subject: Making C++ objects persistent between mex calls, and robust.

From: mathias

Date: 6 Jul, 2011 06:31:09

Message: 21 of 39

Just for the record, in order to complete what has been proposed :

I faced the same issue (which is why I ended up on this thread).

I just want to point out a side problem :

the reinterpret_cast loose the type_id and therefore handling object of a class hierarchy through the mother_class and dynamic_cast is made difficult.

For instance, imagine the class hierachy :
class A {};
class B : public A{};
class C : public B {};

imagine in "mex_function1 " you create
B * pB = new B();
C * pC = new C();

then you send the pointers to matlab, and provide the pointer back to another mex function "mex_function2", and want to use a A * interface :
A * pA = createObjectPointerFromMxArray(prhs[0)

and later on :

pB * = dynamic_cast<B*>(pA) ;
if(NULL!=pB) etc .....

This will not work, since the type_id of the object is lost



As a consequence, I ended up creating a class for storing object.

The class mainly contains a pointer to a map :

class storage
{
public :
 storage();

  object * retrieveObject(string key);
  string registerObject(object * inObject);

  


private :
  static map<string,object * > * _myMap;
}

the storage is used for registering and retrieving objects through a key (string). What is transmitted to matlab and then back to mexes is just the string key. This permits keeping the type_id of created objects.

Then the storage is made global, basically using the following constructor

// static init
 map<string,object * > storage::_myMap =NULL;

// constructor
storage:storage()
{
  if(NULL == _myMap)
 {
 // look for the global adress
   mxArray * mxContainer = mexGetVariable("global","globalObjectStorageAdress");

   if( NULL == mxContainer)
   {
mexPrintf("Storage container does not exist, creating one\n");

_myMap = new map<string,object * >;
         mxContainer = createMxArrayFromObjectPointer(_matlabStorage);

       int status = mexPutVariable("global","globalObjectStorageAdressr",mxContainer);

std::cout << "status " << status;
}
else
{
         mexPrintf("Using existing storage\n");

_myMap = createObjectPointerFromMxArray<map<string,object * >>(mxContainer);
}

    }
}
 
I hope this can help.

Here are the two helpers written by a collegue of mine



template <typename TOBJECT>
TOBJECT * createObjectPointerFromMxArray(const mxArray * inArray) throw (LOCException)
{
if (mxGetClassID(inArray) != mxINDEX_CLASS)
throw LOCException("The input mxArray must be of type mxUINT32_CLASS or mxUINT64_CLASS to store an object pointer.");
if ((mxGetM(inArray) != 1) || (mxGetM(inArray) != 1))
throw LOCException("The input mxArray must be scalar to store an object pointer.");

return *(reinterpret_cast<TOBJECT**>(mxGetData(inArray)));
}



template <typename TOBJECT>
mxArray * createMxArrayFromObjectPointer(TOBJECT * ptrObject)
{
mxArray * outArray = mxCreateNumericMatrix(1, 1, mxINDEX_CLASS, mxREAL);
TOBJECT * * ptrData = reinterpret_cast<TOBJECT**>(mxGetData(outArray));
*ptrData = ptrObject;
return outArray;
}







 






As

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 6 Jul, 2011 09:07:08

Message: 22 of 39

"mathias" wrote:
> the reinterpret_cast loose the type_id and therefore handling object of a class hierarchy through the mother_class and dynamic_cast is made difficult.
>
> For instance, imagine the class hierachy :
> class A {};
> class B : public A{};
> class C : public B {};
>
> imagine in "mex_function1 " you create
> B * pB = new B();
> C * pC = new C();
>
> then you send the pointers to matlab, and provide the pointer back to another mex function "mex_function2", and want to use a A * interface :
> A * pA = createObjectPointerFromMxArray(prhs[0)
>
> and later on :
>
> pB * = dynamic_cast<B*>(pA) ;
> if(NULL!=pB) etc .....
>
> This will not work, since the type_id of the object is lost

I'm not sure I completely understand. If you created an instance of class B and sent it's pointer to MATLAB, why wouldn't you cast it back to a class B pointer when you re-enter a mex file?

If you want to make sure that you are casting a pointer to the correct type then you could use my wrapper class which uses a signature (code given in an earlier thread), and have a different signature for each type.

Oliver

Subject: Making C++ objects persistent between mex calls, and robust.

From: Ajay

Date: 25 May, 2012 03:33:28

Message: 23 of 39

Hello,

I am running in to the same problem and I have a confusion. How did you manage not to go through the Integer->Double->Integer conversions. If I want to return data from mex file back to Matlab i would need to get the pointer to the lhs which is a double pointer. And the same when I pass data from Matlab to mex file. If you could give me some pointers on this it would be very helpful

Thanks,
Ajay


"newuser asdf" wrote in message <ihgtig$df3$1@fred.mathworks.com>...
> "Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <ihgosg$914$1@fred.mathworks.com>...
> > Rune Allnor <allnor@tele.ntnu.no> wrote in message <b3aa9d92-2fe9-4788-a3c0-46ff3e6d6bca@k42g2000yqa.googlegroups.com>...
> >
> > >
> > > When you return back to matlab, you enter a world where
> > > Java is a dominant player. As I understand it, the
> > > matlab user interface (where you access the workspaces etc)
> > > are programmed in Java, in which case the Java interpterer
> > > starts messing things up. And the Java interpterer, too,
> > > interacts with the OS. Not necessarily in exactly the same
> > > way that the C++ compiler does, though.
> >
> > NO, Matlab uses Java engine for graphical purpose only, it does not interact with data, code, internal storing, ... so it does not mess in anyway user data as you assume. Transfer pointers and persistent variable work just fine.
> >
> > Bruno
>
> Thanks for your help - it works now (without Integer->Double->Integer conversions).
> I know that the way I do all this (creating C++ memory leaks, that have to be cleaned up using Matlab...) is not very "clean" programming. But at least it works...
>
> sabine

Subject: Making C++ objects persistent between mex calls, and robust.

From: Pierre

Date: 25 May, 2012 08:38:16

Message: 24 of 39

Well, you actually have two solutions to this problem:
1. Either you go for the pointer-to-integer (or pointer-to-double) and vice versa approach, the integer of which you use as a handle on MATLAB-side
2. or you create a singleton or static storage class which keeps the pointer to your object and from which you can access latter by an explicitly assigned handle (object id or something).

Either way, you would have to get this handle back to MATLAB and keep the handle stored somewhere. For doing so, the wrapper class posted by Oliver is a very good template. I personally ended up with a base class derived from Oliver's class which provides the basic "handle-handling-mechanism" but which can be derived to wrap many different C++ classes very quickly.

Besides that, I'm afraid, I doubt there are other ways for doing this.

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 2 Oct, 2012 15:44:08

Message: 25 of 39

I have recently discovered that if you call
   clear functions
or
   clear all
(which will also clear the functions from memory), when you have created one or more C++ objects in a mex file and passed the pointers back to MATLAB, then MATLAB will crash. You therefore still need to ensure that the relevant mex files are not cleared from memory using the mexLock function.

I have updated my header file to include this functionality, and to improve the checking of the pointer (with usage examples at the bottom):

#include "mex.h"
#include <stdint.h>
#include <string>

#define CLASS_HANDLE_SIGNATURE 0xFF00F0A5
template<class base> class class_handle
{
public:
    class_handle(base *ptr) : ptr_m(ptr), name_m(typeid(base).raw_name()) { signature_m = CLASS_HANDLE_SIGNATURE; }
    ~class_handle() { signature_m = 0; delete ptr_m; }
    bool isValid() { return ((signature_m == CLASS_HANDLE_SIGNATURE) && !strcmp(name_m.c_str(), typeid(base).raw_name())); }
    base *ptr() { return ptr_m; }
    
private:
    uint32_t signature_m;
    std::string name_m;
    base *ptr_m;
};

template<class base> inline mxArray *convertPtr2Mat(base *ptr)
{
    mexLock();
    mxArray *out = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
    *((uint64_t *)mxGetData(out)) = reinterpret_cast<uint64_t>(new class_handle<base>(ptr));
    return out;
}

template<class base> inline class_handle<base> *convertMat2HandlePtr(const mxArray *in)
{
    if (mxGetNumberOfElements(in) != 1 || mxGetClassID(in) != mxUINT64_CLASS || mxIsComplex(in))
        mexErrMsgTxt("Input must be a real uint64 scalar.");
    class_handle<base> *ptr = reinterpret_cast<class_handle<base> *>(*((uint64_t *)mxGetData(in)));
    if (!ptr->isValid())
        mexErrMsgTxt("Handle not valid.");
    return ptr;
}

template<class base> inline base *convertMat2Ptr(const mxArray *in)
{
    return convertMat2HandlePtr<base>(in)->ptr();
}

template<class base> inline void destroyObject(const mxArray *in)
{
    delete convertMat2HandlePtr<base>(in);
    mexUnlock();
}

// Code for init_mex() - ISM3D is my C++ object class, but you use your own
ISM3D *ism = new ISM3D(var1, var2);
plhs[0] = convertPtr2Mat<ISM3D>(ism);

// Code for clear_mex()
destroyObject<ISM3D>(prhs[0]);

// Code for action_mex
ISM3D *ism = convertMat2Ptr<ISM3D>(prhs[0]);
ism->action();

Subject: Making C++ objects persistent between mex calls, and robust.

From: Francesco Montorsi

Date: 7 Nov, 2012 17:19:08

Message: 26 of 39

Dear Oliver,
first of all, thank you very much for writing the initial coincise and clear post. I was searching in google for this problem and reading this thread helped me very much.
Indeed, I managed to interface my C++ class with MATLAB defining a class derived from "handle" in MATLAB and then using new/delete and the convertMat2HandlePtr / convertPtr2Mat methods in C++ .

Just a suggestion: why don't you create a FileExchange contribution with the C++ code and the MATLAB class wrapper? I think it would be very useful to anybody tackling this same issue! :)

Finally, a question about mexLock() and mexUnlock() usage suggested in the last post: it doesn't work for me: mexLock() gets called in convertPtr2Mat() in the init_mex() MEX file, so that it will lock the "init_mex resource", but then mexUnlock() gets called in destroyObject() which is located in the clear_mex() MEX file, and will try to unlock the "clear_mex resource", which is already unlocked. Most important since the mexUnlock() call is located in a different MEX file, the one which called mexLock() will remain locked forever...
did I miss something?
do you implement the clear_mex() and init_mex() functions in the same MEX file? if so, how do you do that (as far as I know, there is only one mexFunction() possible in each MEX file)...

Thank you very much!
Francesco





>
> template<class base> inline class_handle<base> *convertMat2HandlePtr(const mxArray *in)
> {
> if (mxGetNumberOfElements(in) != 1 || mxGetClassID(in) != mxUINT64_CLASS || mxIsComplex(in))
> mexErrMsgTxt("Input must be a real uint64 scalar.");
> class_handle<base> *ptr = reinterpret_cast<class_handle<base> *>(*((uint64_t *)mxGetData(in)));
> if (!ptr->isValid())
> mexErrMsgTxt("Handle not valid.");
> return ptr;
> }
>
> template<class base> inline base *convertMat2Ptr(const mxArray *in)
> {
> return convertMat2HandlePtr<base>(in)->ptr();
> }
>
> template<class base> inline void destroyObject(const mxArray *in)
> {
> delete convertMat2HandlePtr<base>(in);
> mexUnlock();
> }
>
> // Code for init_mex() - ISM3D is my C++ object class, but you use your own
> ISM3D *ism = new ISM3D(var1, var2);
> plhs[0] = convertPtr2Mat<ISM3D>(ism);
>
> // Code for clear_mex()
> destroyObject<ISM3D>(prhs[0]);
>
> // Code for action_mex
> ISM3D *ism = convertMat2Ptr<ISM3D>(prhs[0]);
> ism->action();

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 8 Nov, 2012 10:27:08

Message: 27 of 39

"Francesco Montorsi" wrote:
> Just a suggestion: why don't you create a FileExchange contribution with the C++ code and the MATLAB class wrapper? I think it would be very useful to anybody tackling this same issue! :)

Good idea. I've just submitted it, so it will appear shortly.
 
> Finally, a question about mexLock() and mexUnlock() usage suggested in the last post: it doesn't work for me: mexLock() gets called in convertPtr2Mat() in the init_mex() MEX file, so that it will lock the "init_mex resource", but then mexUnlock() gets called in destroyObject() which is located in the clear_mex() MEX file, and will try to unlock the "clear_mex resource", which is already unlocked. Most important since the mexUnlock() call is located in a different MEX file, the one which called mexLock() will remain locked forever...
> did I miss something?
> do you implement the clear_mex() and init_mex() functions in the same MEX file? if so, how do you do that (as far as I know, there is only one mexFunction() possible in each MEX file)...

Ah, good point. In fact I do have just one mex function, and I access the various class methods using a command string. I mention this earlier in the thread, and you will see this in the example code.

Oliver

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 9 Nov, 2012 09:22:14

Message: 28 of 39


> "Francesco Montorsi" wrote:
> > Just a suggestion: why don't you create a FileExchange contribution with the C++ code and the MATLAB class wrapper? I think it would be very useful to anybody tackling this same issue! :)

"Oliver Woodford" wrote:
> Good idea. I've just submitted it, so it will appear shortly.

An example mex file and MATLAB wrapper class can now be found at:
http://www.mathworks.com/matlabcentral/fileexchange/38964

Feedback welcome, preferably via this post or the "Contact Author" link on my Author page.

Oliver

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver

Date: 21 Jan, 2013 16:27:08

Message: 29 of 39

> "Oliver Woodford" wrote:
> > Good idea. I've just submitted it, so it will appear shortly.
>
> An example mex file and MATLAB wrapper class can now be found at:
> http://www.mathworks.com/matlabcentral/fileexchange/38964
>
> Feedback welcome, preferably via this post or the "Contact Author" link on my Author page.
>
> Oliver

Oliver: first off, this way of making C++ objects persistent is exactly what I was looking for. Thank you very much for the example!

I'm assuming of course that I'll be able to get it to work, which it isn't for me right now... Warning, I'm almost a complete newbie in C/C++ so I may be doing something stupid.

All I want to due is to associated a double variable with the dummy class so that the variable is persistent. Here's what I do:

I change the dummy class to:

class dummy
{
public:
void set(double *input) {
this->data = (double*) mxCalloc(1, sizeof(double));
mexMakeMemoryPersistent(this->data);
this->data = input;
}
double get() { return *this->data; }
void freedata(void) { mxFree(this->data); }
private:
double *data;
};


The "set" part of mexFunction is:

if (!strcmp("set", cmd)) {
val = mxGetPr(prhs[2]);
dummy_instance->set(val);
return;
}


The "get" part of mexFunction is:

if (!strcmp("get", cmd)) {
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
val = mxGetPr(plhs[0]);
val[0] = dummy_instance->get();
        return;
}


The "delete" part of mexFunction is changed to:
if (!strcmp("delete", cmd)) {
// free memory
dummy_instance->freedata();

        // Destroy the C++ object
        destroyObject<dummy>(prhs[1]);
        return;
}

some example runs:
> a = class_interface(3.3);
> get(a)
ans = 3.3
> b = class_interface(3.5);
> get(b)
ans = 3.5
> get(a)
ans = 3.5

So the two objects are somehow sharing memory?? And then sometimes (not always) when I clear the variables, matlab crashes. After a few crashes, Matlab won't start and I have to delete the preferences folder, restart my computer and only then am I able to start Matlab (as per http://www.mathworks.com/matlabcentral/answers/51828)

I'd appreciate any advice that anybody can give.

Thanks!
Oliver

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver

Date: 21 Jan, 2013 16:36:08

Message: 30 of 39

> The "set" part of mexFunction is:
>
> if (!strcmp("set", cmd)) {
> val = mxGetPr(prhs[2]);
> dummy_instance->set(val);
> return;
> }

I forgot to mention, set is called within the constructor in class_interface.m:
function this = class_interface(varargin)
    this.objectHandle = class_interface_mex('new', varargin{:});
    class_interface_mex('set', this.objectHandle, varargin{:});
end
        

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 21 Jan, 2013 23:05:09

Message: 31 of 39

Oliver, you have made an error in your set function. The last line of the function should be changed as follows:

  void set(double *input) {
  this->data = (double*) mxCalloc(1, sizeof(double));
  mexMakeMemoryPersistent(this->data);
  *this->data = *input;
  }

Do you see why?

However, by allocating memory and not freeing it in a destructor, you leave your code open to memory leaks. In fact, before I fixed the bug above, your code *was* leaking memory. I would rewrite the dummy class to be much simpler and avoid any leaks, as follows:

class dummy
{
public:
void set(double input) { data = input; }
double get() { return data; }
private:
double data;
};

The "set" part of mexFunction is then:
if (!strcmp("set", cmd)) {
     dummy_instance->set(mxGetScalar(prhs[2]));
     return;
}

The "get" part of mexFunction is:
if (!strcmp("get", cmd)) {
        plhs[0] = mxCreateDoubleScalar(dummy_instance->get());
        return;
}

The "delete" part of mexFunction is changed to:
if (!strcmp("delete", cmd)) {
        // Destroy the C++ object
        destroyObject<dummy>(prhs[1]);
        return;
}

Much simpler! Hope that helps.
Oliver

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver

Date: 22 Jan, 2013 00:15:09

Message: 32 of 39

Thanks Oliver, for the fast reply! It works well now. Below are questions for my understanding only, so low priority if you're busy.

"Oliver Woodford" wrote in message <kdkhj5$8v5$1@newscl01ah.mathworks.com>...
> Oliver, you have made an error in your set function. The last line of the function should be changed as follows:
...

> *this->data = *input;
>
> Do you see why?

They were both pointers, so to copy they need to be de-referenced?

Yes, your code is much simpler and straightforward. I thought I was freeing the memory in a destructor by calling freedata (which executed mxFree) in the first part of the "delete". Why didn't this work properly?

And why isn't mexMakeMemoryPersistent needed? Is it the mexLock in class_handle.hpp that is making everything in the class object persistent?

Thanks again, Oliver!

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 22 Jan, 2013 10:07:06

Message: 33 of 39

"Oliver" wrote:
> They were both pointers, so to copy they need to be de-referenced?

Exactly. You want to copy the value, not the pointer.

> Yes, your code is much simpler and straightforward. I thought I was freeing the memory in a destructor by calling freedata (which executed mxFree) in the first part of the "delete". Why didn't this work properly?

Firstly freedata is a member function, but not the destructor (which would be ~dummy()), so you have to remember to call it everywhere that an object of that class is destroyed, whereas the destructor gets called automatically. Secondly, since you were overwriting the pointer reference returned by mxCalloc, you were not then able to free that memory.

> And why isn't mexMakeMemoryPersistent needed? Is it the mexLock in class_handle.hpp that is making everything in the class object persistent?

Memory allocated using new is not kept track of by MATLAB, so it is not freed when the mex function is exited. However, it is freed when the mex file is cleared from memory, which is why you need the mexLock.

Subject: Making C++ objects persistent between mex calls, and robust.

From: Gabri Gwala

Date: 30 Jan, 2013 17:47:08

Message: 34 of 39

Many thanks to Oliver Woodford and all the other contributors of this effective strategy. Anyway I would like to submit a potential issue when using Matlab Parallel Computation Toolbox. In particular i'm trying to use this scheme inside a parfor, obtaining a segmentation fault while trying to convert a matlab handle in C++ pointer.
Since this is not a pure Matlab topic, I posted the detailed question on stackoverflow.

http://stackoverflow.com/questions/14607109/matlab-c-segmentation-fault-on-parallel-computing-with-c-mex-persistent-obj

Regards,
Gabriele Gualandi

Subject: Making C++ objects persistent between mex calls, and robust.

From: Steven_Lord

Date: 30 Jan, 2013 22:23:08

Message: 35 of 39



"Gabri Gwala" <djgwla-aux@yahoo.it> wrote in message
news:kebmas$kjs$1@newscl01ah.mathworks.com...
> Many thanks to Oliver Woodford and all the other contributors of this
> effective strategy. Anyway I would like to submit a potential issue when
> using Matlab Parallel Computation Toolbox. In particular i'm trying to use
> this scheme inside a parfor, obtaining a segmentation fault while trying
> to convert a matlab handle in C++ pointer.
> Since this is not a pure Matlab topic, I posted the detailed question on
> stackoverflow.
>
> http://stackoverflow.com/questions/14607109/matlab-c-segmentation-fault-on-parallel-computing-with-c-mex-persistent-obj

I'm not an expert in Parallel Computing Toolbox and referring to C++ objects
in MATLAB, but I'm doubtful this will work without significant modification.

Remember that in Parallel Computing Toolbox, workers are separate instances
of MATLAB from the client. There's a reason they have the same icon as the
MATLAB client session in step 3 of the description of a PARFOR loop:

http://www.mathworks.com/help/distcomp/introduction-to-parallel-solutions.html#brjw1fx-1

This means that the value representing a pointer to the C++ object in your
client session probably won't point to your C++ object on the workers, and
even if it did (for local workers on the same machine) that memory would
probably belong to the MATLAB client session (possibly leading to the
segmentation violation given in your Stack Overflow posting.)

Think of this like the handle to a figure on the client. When that handle
gets passed to the workers, the workers can't use that handle to affect the
client's figure window -- it's the client's handle!

If your C++ object had a small amount of state, returning a struct array or
cell array from the MEX-file containing the state necessary to reconstitute
the object might be an option (since MATLAB knows how to pass structs
between the client and the workers) but that kind of defeats the purpose of
having a C++ object.

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 31 Jan, 2013 11:56:08

Message: 36 of 39

"Gabri Gwala" wrote:
> Many thanks to Oliver Woodford and all the other contributors of this effective strategy. Anyway I would like to submit a potential issue when using Matlab Parallel Computation Toolbox. In particular i'm trying to use this scheme inside a parfor, obtaining a segmentation fault while trying to convert a matlab handle in C++ pointer.
> Since this is not a pure Matlab topic, I posted the detailed question on stackoverflow.
>
> http://stackoverflow.com/questions/14607109/matlab-c-segmentation-fault-on-parallel-computing-with-c-mex-persistent-obj
>
> Regards,
> Gabriele Gualandi

If all your workers are threads on the same computer then you might be able to solve the problem by making the class instance and all the memory allocated by it in shared memory, e.g. by using the approach described here:
http://www.boost.org/doc/libs/1_51_0/doc/html/interprocess/sharedmemorybetweenprocesses.html

If the workers are on different computers, then, as Steve points out, this won't work.

Subject: Making C++ objects persistent between mex calls, and robust.

From: Gabri Gwala

Date: 22 Sep, 2013 15:09:07

Message: 37 of 39

"Oliver Woodford" wrote in message <kedm4o$7ns$1@newscl01ah.mathworks.com>...
> "Gabri Gwala" wrote:
> > Many thanks to Oliver Woodford and all the other contributors of this effective strategy. Anyway I would like to submit a potential issue when using Matlab Parallel Computation Toolbox. In particular i'm trying to use this scheme inside a parfor, obtaining a segmentation fault while trying to convert a matlab handle in C++ pointer.
> > Since this is not a pure Matlab topic, I posted the detailed question on stackoverflow.
> >
> > http://stackoverflow.com/questions/14607109/matlab-c-segmentation-fault-on-parallel-computing-with-c-mex-persistent-obj
> >
> > Regards,
> > Gabriele Gualandi
>
> If all your workers are threads on the same computer then you might be able to solve the problem by making the class instance and all the memory allocated by it in shared memory, e.g. by using the approach described here:
> http://www.boost.org/doc/libs/1_51_0/doc/html/interprocess/sharedmemorybetweenprocesses.html
>
> If the workers are on different computers, then, as Steve points out, this won't work.

As Edric suggested on StackOverflow, the solution to my previous problem was simply that I had to perform a deep copy at C++ side and transfer all the data thru numeric arrays at Matlab side. Adopting a deep copy, this framework really works good also in parallel computing.

However there is something unclear to me:

1)
I see that at every invocation of a function on the interface, a new instance of class CLASS_HANDLE is created (since is called convertPtr2Mat). This class offers also a destroyer, but I cannot see where it is called.

2)
Every time an instance of CLASS_HANDLE is created, its constructor calls mexLock(): Is this really necessary, since the whole code is compiled as a single MEX-function?

3)
The usage of the wrapping class CLASS_HANDLE is necessary for the interface to work, or it only provides usefull auxilary methods, for example the check !ptr->isValid()?

Thank you!!

Subject: Making C++ objects persistent between mex calls, and robust.

From: Gabri Gwala

Date: 22 Sep, 2013 15:34:07

Message: 38 of 39

"Gabri Gwala" <djgwla-aux@yahoo.it> wrote in message <l1n16j$19e$1@newscl01ah.mathworks.com>...
> "Oliver Woodford" wrote in message <kedm4o$7ns$1@newscl01ah.mathworks.com>...
> > "Gabri Gwala" wrote:
> > > Many thanks to Oliver Woodford and all the other contributors of this effective strategy. Anyway I would like to submit a potential issue when using Matlab Parallel Computation Toolbox. In particular i'm trying to use this scheme inside a parfor, obtaining a segmentation fault while trying to convert a matlab handle in C++ pointer.
> > > Since this is not a pure Matlab topic, I posted the detailed question on stackoverflow.
> > >
> > > http://stackoverflow.com/questions/14607109/matlab-c-segmentation-fault-on-parallel-computing-with-c-mex-persistent-obj
> > >
> > > Regards,
> > > Gabriele Gualandi
> >
> > If all your workers are threads on the same computer then you might be able to solve the problem by making the class instance and all the memory allocated by it in shared memory, e.g. by using the approach described here:
> > http://www.boost.org/doc/libs/1_51_0/doc/html/interprocess/sharedmemorybetweenprocesses.html
> >
> > If the workers are on different computers, then, as Steve points out, this won't work.
>
> As Edric suggested on StackOverflow, the solution to my previous problem was simply that I had to perform a deep copy at C++ side and transfer all the data thru numeric arrays at Matlab side. Adopting a deep copy, this framework really works good also in parallel computing.
>
> However there is something unclear to me:
>
> 1)
> I see that at every invocation of a function on the interface, a new instance of class CLASS_HANDLE is created (since is called convertPtr2Mat). This class offers also a destroyer, but I cannot see where it is called.
>
> 2)
> Every time an instance of CLASS_HANDLE is created, its constructor calls mexLock(): Is this really necessary, since the whole code is compiled as a single MEX-function?
>
> 3)
> The usage of the wrapping class CLASS_HANDLE is necessary for the interface to work, or it only provides usefull auxilary methods, for example the check !ptr->isValid()?
>
> Thank you!!

Sorry, I have to correct my previous sentence #2: mexLock() is not called from the constructor of CLASS_HANDLE, but just before creating a new instance of CLASS_HANDLE. However what I want to highlight is that this happens every time a function is invoked on the interface.

Subject: Making C++ objects persistent between mex calls, and robust.

From: Oliver Woodford

Date: 27 Sep, 2013 10:54:06

Message: 39 of 39

"Gabri Gwala" wrote:
> There is something unclear to me:
>
> 1)
> I see that at every invocation of a function on the interface, a new instance of class CLASS_HANDLE is created (since is called convertPtr2Mat). This class offers also a destroyer, but I cannot see where it is called.

The destructor is called automatically when using delete, on the first line of the destroyObject() function, which is called on line 37 of class_mex_interface.cpp.

> 2)
> mexLock() is called just before creating a new instance of CLASS_HANDLE.

Yes.

> This happens every time a function is invoked on the interface.

No. Why do you think that?
 
> 3)
> The usage of the wrapping class CLASS_HANDLE is necessary for the interface to work, or it only provides useful auxiliary methods, for example the check !ptr->isValid()?

It simply provides a means of checking that you are not casting a random memory address to a pointer to an instance of the base class. Doing that could lead to some bad things happening, so it is a protection against that.

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us