Effacer les filtres
Effacer les filtres

Simple mex function help

1 vue (au cours des 30 derniers jours)
Nicholas
Nicholas le 15 Juil 2014
Modifié(e) : Nicholas le 16 Juil 2014
Solved

Réponse acceptée

James Tursa
James Tursa le 15 Juil 2014
Modifié(e) : James Tursa le 15 Juil 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 commentaires
Nicholas
Nicholas le 15 Juil 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 le 15 Juil 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Write C Functions Callable from MATLAB (MEX Files) dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by