Simple mex function help

조회 수: 1 (최근 30일)
Nicholas
Nicholas 2014년 7월 15일
편집: Nicholas 2014년 7월 16일
Solved

채택된 답변

James Tursa
James Tursa 2014년 7월 15일
편집: James Tursa 2014년 7월 15일
You have defined x and y in mexFunction to be pointers to double, not double. But your xtimes10 routine is expecting double, not pointer to double. Hence the error. Also, unrelated, you create plhs[0] twice which is unnecessary. One way to fix things is to have the xtimes10 routine work with pointers, and dereference them inside the routine. E.g.,
#include "mex.h" // Matlab mex header file
// C function multiply arrays x and y (of size) to give z
void xtimes10(double *x, double *y)
{
*y = *x * 10;
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *x,*y;
x = mxGetPr(prhs[0]);
plhs[0] = mxCreateDoubleMatrix( 1 , 1, mxREAL);
y = mxGetPr(plhs[0]);
xtimes10(x,y);
mexPrintf("result y= %g\n", y);
}
Also you will notice that I fixed your mexPrintf call. It was named incorrectly, and you were using the wrong format for a double (%d is for integer types), and you did not have a newline.
  댓글 수: 8
Nicholas
Nicholas 2014년 7월 15일
Thanks for that clarification. On another note... I typed LocalInfo in the command window and got a MATLAB System Error notification... Am I just not supposed to be able to call LocalInfo from the command window or is there a problem with the mex?
James Tursa
James Tursa 2014년 7월 15일
If you type LocalInfo with no input, then yes you will get a crash because prhs[0] is not defined but LocalInfo tries to access it. That is why I made the point of "bare bones". To be production quality code (i.e., not crash MATLAB), you would need to put in checks for this, which can take up a lot of code but is necessary to be robust. E.g.,
if( nrhs != 1 ) {
mexErrMsgTxt("Expecting exactly one input");
}
if( !mxIsStruct(prhs[0]) ) {
mexErrMsgTxt("Input must be a struct");
}
etc etc
Basically, you need to check that the number of inputs is as expected, that the class of the inputs is as expected, that the sizes are as expected, that the fields you expect to be there are actually there, that the fields are not empty, etc. etc. I.e., you need to check everything before you use it. I leave that up to you.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by