Calling methods of C++ class in MEX from MATLAB

后端 未结 5 2133
一向
一向 2021-01-03 09:59

I have a DLP kit which I need to control via MATLAB using a C++ API.

Say, I have functions/methods using C/C++ for {load_data, load_settings,display_data}

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-03 10:52

    The easiest is to design a MEX wrapper that keeps an instance of the class object, and dispatch a call to that MEX binary. I have made a library for those trying to develop a MEX wrapper in C++.

    https://github.com/kyamagu/mexplus

    Here is a quick snippet.

    // C++ class to be wrapped.
    class Database;
    // Instance session storage.
    template class mexplus::Session;
    // Constructor.
    MEX_DEFINE(new) (int nlhs, mxArray* plhs[],
                     int nrhs, const mxArray* prhs[]) {
      InputArguments input(nrhs, prhs, 1);
      OutputArguments output(nlhs, plhs, 1);
      output.set(0, Session::create(
          new Database(input.get(0))));
    }
    // Destructor.
    MEX_DEFINE(delete) (int nlhs, mxArray* plhs[],
                        int nrhs, const mxArray* prhs[]) {
      InputArguments input(nrhs, prhs, 1);
      OutputArguments output(nlhs, plhs, 0);
      Session::destroy(input.get(0));
    }
    // Member method.
    MEX_DEFINE(query) (int nlhs, mxArray* plhs[],
                       int nrhs, const mxArray* prhs[]) {
      InputArguments input(nrhs, prhs, 2);
      OutputArguments output(nlhs, plhs, 1);
      const Database& database = Session::getConst(input.get(0));
      output.set(0, database.query(input.get(1)));
    }
    // And so on...
    MEX_DISPATCH
    

提交回复
热议问题