Simple mex function help

1 次查看(过去 30 天)
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