I have a c++ program that updates a system. When I wrote everything in C++ it looked a little something like this
System S; //initialize a System object 'S'
while (notFinished)
{
S.update1(inputVars1);
S.update2(inputVars2);
}
Now I would like to call the individual update functions from matlab and be able to use access functions (written in c++) to view the state of the program at any time when debugging in matlab.
So matlab will need to call something to instantiate a “System” object, and then it will need to call individual System methods from the original system object.
Suppose I compile separate mex files to Initialize update1 update2 and some that get information about the current state getState. And then write some matlab code…
%matlab main
S = Initalize(); %mex file
while (notFinished)
update1(S); %mex file
keyboard; % access state information using "getState" mex function
update2(S); %mex file
keyboard; % access state information using "getState" mex function
end
Will this essentially allow me to call and debug my C++ program algorithms in Matlab, or is there another way to go about this whole problem?
The way I would do it is by creating a pointer for System in C++ in the Initialize mex function using “new”. If you are on a 64 bit platform then cast this pointer to a 64-bit integer and create an mxArray with that type and value. Return this mxArray from your Initialize function.
For later calls to your other mex files you should pass this mxArray as an input. Inside those files you can cast it back as a pointer and call methods on the object.
I also would take one more step to wrap this whole thing inside a MATLAB System object or a regular object and not expose the pointer value S outside the object. You need methods on the object which would call your mex files. This is especially needed if you are planning to give this to other people for use. Others might accidentally overwrite or modify S causing crashes.
Finally you need a delete mex function which would delete the pointer S. If you create a handle class then you can do this in the destructor.