Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interacting with C++ objects through Mex files

Tags:

c++

matlab

mex

I'm a bit stuck on if my current goal is feasible, and if so, how to do this. I'm hoping to interact with some C++ classes through a Mex file, but I would need the instances of the objects I am accessing to be persistent across calls from different Mex functions. For example, suppose I do the following within an initialization Mex file:

void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    size_t nCats = (size_t) *mxGetPr(prhs[0]);

    std::vector<Cat> cats;
    for(size_t i = 0; i <nCats; i++){
         cats[i] = Cat(/* arguments to constructor*/);
    }
}

So I've initialized my Cat objects from my external C++ code. Now, later down the line, I need to update info about my Cat objects, so in a different Mex file I have

void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

     for(size_t i = 0; i < nCats; i++){
          cats[i].feed(/*parameters to feed method*/);
     }
}

Here are my questions:

  1. How would I make this std::vector persist across calls to different Mex files? There isn't a way to return non-Matlab types from Mex files (that I'm aware of), and Mathworks says that local variables within Mex functions are generally garbage collected when the function returns, which I do not want. How can I call the same std::vector with the stored objects I am interested in across different functions? Or even calls to the same function?

  2. Is there a better way to do this with Matlab? Essentially I'm trying to use Matlab to drive some C++ code, which does the heavy lifting, and then brings it all back to Matlab for analysis. The trouble is that the C++ code is already written, and I need to try to bend Matlab to fit those classes.

like image 262
Matt Avatar asked Oct 29 '22 00:10

Matt


1 Answers

Not sure if possible between Mex functions but you can make some things persistent between calls to the same mex routine.

See documentation for:

  • mexMakeMemoryPersistent

  • mexMakeArrayPersistent

Also see this answer on the Mathworks site: How can I make memory persistent between calls to a MEX-file in MATLAB

I have not done this myself so can't give more specific help but this might point you in the right direction.

like image 94
Aero Engy Avatar answered Nov 15 '22 07:11

Aero Engy