NSZ
NSZ

Reputation: 235

C++ mex file bug with output

I am kinda new to mex files and I am trying to create a function in c++ to speed up calculations. However I encounter some bug that crashes Matlab and I don't understand why.

I tried to debug many times and in the end I found that the problem lies in functions outside the main mexFunction, however I don't know how to solve it. I created a sample code to illustrate the problem:

#include <iostream>
#include <mex.h>

double simplesum (double a, double b){
    double sum; 
    sum = a+b;
    return(sum);
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
    double *a, *b,*out;
    a = mxGetPr(prhs[0]);
    b = mxGetPr(prhs[1]);
    out = mxGetPr(plhs[0]);
    double sum;
    sum=simplesum(*a,*b);
    *out = sum;
}

If I don't call the function simplesum everything works, but I would like to use it (in my more complicated code).

Is there a problem with memory allocation or something else?

Upvotes: 1

Views: 83

Answers (2)

Gelliant
Gelliant

Reputation: 1845

You can also directly get the right hand side values with mxGetScalar. Out can point to the 1x1 matrix of double precision values.

#include <iostream>
#include <mex.h>

double simplesum (double a, double b,double *out){
    out[0] = a+b;
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
    double a, b, *out;
    plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
    a = mxGetScalar(prhs[0]);
    b = mxGetScalar(prhs[1]);
    out = mxGetPr(plhs[0]);
    simplesum(a,b,out);
}

Upvotes: 2

Ander Biguri
Ander Biguri

Reputation: 35525

There is a problem with memory allocation: there is none.

You need to create the variable in MATLAB (mex) you can not just assign a variable to a pointer and hope that it catches it.

Among the different ways of doing it, one is mxCreateNumericMatrix

mxArray *mxCreateNumericMatrix(mwSize m, mwSize n, 
  mxClassID classid, mxComplexity ComplexFlag);

So your code would need to have:

plhs[0] = mxCreateNumericMatrix(1, 1, mxDOUBLE_CLASS, mxREAL); // "malloc"

out = mxGetPr(plhs[0]); // Make the output pointer to be "out"
double sum;
sum=simplesum(*a,*b);
out = &sum;   // Make out be the same address as sum.

Upvotes: 1

Related Questions