Simple mex function help

3 visualizaciones (últimos 30 días)
Nicholas
Nicholas el 15 de Jul. de 2014
Editada: Nicholas el 16 de Jul. de 2014
Solved

Respuesta aceptada

James Tursa
James Tursa el 15 de Jul. de 2014
Editada: James Tursa el 15 de Jul. de 2014
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 comentarios
Nicholas
Nicholas el 15 de Jul. de 2014
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 el 15 de Jul. de 2014
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by