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

조회 수: 28 (최근 30일)
shdotcom shdotcom
shdotcom shdotcom 2019년 9월 22일
편집: James Tursa 2019년 9월 23일
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 valueme
Is it possible to improve mexFunction for better performance?

답변 (1개)

James Tursa
James Tursa 2019년 9월 22일
Put this at the bottom of your code. But remember that if you call mexErrMsgTxt your mex function will exit immediately and not return any value, so if you want to see the result you should delete the code that calls mexErrMsgTxt.
plhs[0] = mxCreateDoubleScalar(result);
  댓글 수: 2
shdotcom shdotcom
shdotcom shdotcom 2019년 9월 23일
편집: shdotcom shdotcom 2019년 9월 23일
Thank you very much. What if I want to return an array of more than one values (with different types), instead of a value?
James Tursa
James Tursa 2019년 9월 23일
편집: James Tursa 2019년 9월 23일
Then you will have to copy the values one-by-one. E.g.,
double *dp, *pr;
int i, n;
// some code here to allocate and assign n values to dp[0], dp[1], etc.
plhs[0] = mxCreateDoubleMatrix(1,n,mxREAL);
pr = mxGetPr(plhs[0]);
for( i=0; i<n; i++ ) {
pr[i] = dp[i];
}
mxFree(dp);
Or you could use memcpy( ) to copy everything as a block.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by