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=mxCreateDoublematrix(1,1,mxREAL); double *resultPtr = mxGetPr(plhs); *(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; 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?