0

I have an instance of a class and I want to pass it to a function using mexCallMATLAB function.

The class is originally in Matlab but since the data is in my C++ wrapper, I used this approach and pack my data to it. Therefore type of final object is mwArray (look mentioned link and GlobalData class which is in Matlab and globals instance which is in C++). But mexCallMATLAB function uses mxArray *.

How can transfer data of a mwArray * to mwArray *? If the types was simple it can easy done with manual transferring. For example creating a double array of mxArray and manually copy the data to it. But in this situation the data is a class of multiple data fields/type.

More generally how can pass a class to a Matlab function from C++ wrapper?

Suppose this is the class in Matlab

classdef GlobalData < handle

    properties
        val1
        val2
        val3
    end
end

This is the Matlab function that I compiled via mcc and used for wrap the class.

function globals = create_globals()

    globals = GlobalData();
    globals.val1 = 2;
    globals.val2 = 5.25;
    globals.val3 = 'data name';
end

This is the C++ code that has the data. Here we use the previous method to create a instance of GlobalData and the pass it to Matlab function myCallback.

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    // ...
    mwArray globals;
        try {

            // Pack data to a single Container class of type GlobalData
            create_globals(1, globals);

        } catch (const mwException& e) {
            cerr << e.what() << endl;
            return;
        } catch (...) {
            cerr << "Unexpected error thrown" << endl;
            return;
        }

        int nlhs1 = 1, nrhs1 = 2;
        mxArray *plhs1[1], *prhs1[2];

        // First parameter of myCallback set to a arbitrary double value
        prhs1[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
        *mxGetPr(prhs1[0]) = .6;

        // Here prhs1[1] must set to globals
        // ??? prhs1[1] = globals ???

        mexCallMATLAB(nlhs1, plhs1, nrhs1, prhs1, "myCallback");
    // ...
}
Community
  • 1
  • 1
Bonje Fir
  • 787
  • 8
  • 25

1 Answers1

0

You can extract the mxArray * by using the GetData() method.

   mwArray *A;
   mxArray *B;

   B = A->GetData();
Rama
  • 3,222
  • 2
  • 11
  • 26
  • `GetData` method takes two input. `buffer` and `size`. Therefore `B = A->GetData();` must change to `A->GetData(B, sizeof(A));` But this code gets `cannot convert argument 1 from 'mxArray *' to 'mxDouble *'` – Bonje Fir Feb 14 '17 at 04:50