简体   繁体   中英

How to return the outputs of mexFunction() in Matlab?

I have this code in C:

#include <mex.h>
#include <matrix.h>
#include<stdio.h>
#include <math.h>

//...

 int callFun(int argc, char *argv[]){
     int aa = 4;
     printf ( "\naa value = %d\n",aa);
 return aa;
 }

//...

and I want to call it using Matlab. To do this, I have created this mexFunction()

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
    {
    int argc = 0;
    char **argv;
    int i, result;

    argc = nrhs;
    argv = (char **) mxCalloc( argc, sizeof(char *) );

    for (i = 0; i < nrhs; i++){
        if( !mxIsChar( prhs[i] ) ){
        mexErrMsgTxt("Input must be of type char.");
        return;
        }
        argv[i] = mxArrayToString( prhs[i] );
    }

    result = callFun( argc, argv );

    for( i=argc-1; i>=0; i-- )
        mxFree( argv[i] );

    mxFree( argv );
    if( result )
        mexErrMsgTxt("main function causes an error");
}

However, I do not know how to get aa value, when I call callFun() in Matlab.

>> Outputs = callFun('callFun','ff');  % this should returns aa value

Is it possible to improve mexFunction for better performance?

You can use mxCreateDoubleScalar :

plhs[0] = mxCreateDoubleScalar((double)result);

I suggest you cast the value to double , as that is MATLAB's native type. You can pass the int as int32 to MATLAB, but that is more involved and not as convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM