MATLAB: How to get a Class Object of C++, which is created in Mex function, after running the Mex

mex c++ class object

Hi, I have 2 mex functions compiled from C++. In the first one, it creates Class Object of C++ and the second one does the next work by the same Class Object. I tried(e.g. used persistent, mexMakeMemoryPersistent), but it seems I can not get the Class Object created in the first mex. Did anyone know how to do? PS. It works correctly when I combine the two mex functions, but I must separate them in order to call the second one circularly in my script.
//the first mex
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
if(nrhs!=0)
{
mexPrintf("do not need argument!\n");
}
else
{
CBodyBasics * classExample=new CBodyBasics;
HRESULT hr;
hr=classExample->InitializeDefaultSensor();
if (FAILED(hr))
{
printf("err in starting!\n");
return;
}
}
}

Best Answer

Assuming both dlls are compiled with the exact same options with the same compiler, you could just pass the CBodyBasics* pointer maskerading as an uint64 between the two dlls.
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) {
CBodyBasics* classExample = new CBodyBasics;
HRESULT hr = classExample->InitializeDefaultSensor();
plhs[0] = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL)
uint64_T* ptr = static_cast<uint64_T*>(mxGetData(plhs[0]));
*ptr = reinterpret_cast<uint64_T>(classExample);
}
void mexFunction2(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) {
uint64_T* ptr = static_cast<uint64_T*>(mxGetData(mxGetPr(prhs[0]));
CBodyBasics* classExample = reinterpret_cast<CBodyBasics*>(*ptr);
}
Or something like that (with checks on nlhs, nrhs, size and types of inputs, etc.).
As said, you need to make sure that both dlls are compiled exactly with the same options so that the memory layout of your class is the same in both, otherwise you may get crashes or worse.