Search code examples
c++matlabmex

Assign float * or int * to mxArray


I got a typical cpp function in matlab using mex

#include "mex.h"

void func (int * rowvec, int * colvec, float * valvec, int * nnz){/*fill arguments*/}



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

where I check that in I have enough output variables available

if(nlhs != 4) {
  mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs",
                  "Four outputs required.");
}

Furthermore, in this function I declare four variables:

int *rowvec;        /* 1st output array */
int *colvec;        /* 2nd output array */
float *valvec;      /* 3rd output array */
int *nnz;           /* 4th output scalar */

They will be defined/filled in a function:

func(rowvec, colvec, valvec, nnz) //arguments get filled with values

Now I want to do something like that:

plhs[0] = rowvec;
plhs[1] = colvec;
plhs[2] = valvec;
plhs[3] = nnz;

It unfortunately throws four understandable errors, because those are two different data types. The errors are like this:

cannot convert ‘int*’ to ‘mxArray* {aka mxArray_tag*}’ in assignment plhs[0] = rowvec;

How can I fix this?


Solution

  • You missed a step.

    You need to use mxCreateNumericArray and assign that to your output arguments.

    Then use mxGetData on the created arrays and set your int/float pointers to that.

    Then call func to fill the outputs.

    plhs[0] = mxCreateNumericArray(ndim, *dims, classid, ComplexFlag);
    ...
    rowvec=(int*)mxGetData(plhs[0]);
    ...
    func(rowvec, colvec, valvec, nnz);
    

    If you can change the interface, you might want to consider func(plhs) instead. You will need to know the size of the output arrays before you can use the pointers.