我编写了一个mex函数(在C中),它将2个数组和一个标量作为输入,在进行一些数学计算后,它返回一个标量作为输出 . 我可以在MATLAB平台上成功编译相应的mex函数,但是一旦我用一些输入数据运行它,就会导致MATLAB崩溃 . 错误日志的 Headers 是“在4月25日星期一检测到的分段违例...:..:.. 2016” . 我还尝试使用GNU调试器'gdb'在Linux平台上调试它 . 它显示了我使用nrhs,prhs [],nlhs,plhs []验证输入/输出参数的数量和类型的所有if语句的问题 . 例如,我检查输入参数数量的第一个语句是,
if(nrhs!=3)
mexErrMsgTxt("Error..Three inputs required.");
还有其他人为nlhs . GNU调试器将其第一个断点放在上面的if语句中,如果我正在对它进行注释,则会导致第二个if语句出现问题,同样如此 . 当我注释掉所有if语句时,mex函数成功运行并且还给出了所需的输出 .
我已经很久没有通过阅读所有可用的答案来删除这个错误,但我不能这样做 . 请帮助我解决上述问题 . 提前致谢 .
以下是实际代码:
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
double *Ip, *Is; /* Input data vectors */
double r; /* Value of r (input) */
double *dist; /* Output ImED distance */
size_t ncols; /* For storing the size of input vector */
/* Checking for proper number of arguments */
if(nrhs!=3)
mexErrMsgTxt("Error..Three inputs required.");
if(nlhs!=1)
mexErrMsgTxt("Error..Only one output required.");
/* make sure the first input argument(value of r) is scalar */
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1 )
mexErrMsgTxt("Error..Value of r must be a scalar.");
/* make sure that the input vectors are of type double */
if(!mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || !mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]))
mexErrMsgTxt("Error..Input vectors must be of type double.");
/* Make sure that the output is of type double and is a scalar */
if(!mxIsDouble(plhs[0]) || mxIsComplex(plhs[0]) || mxGetNumberOfElements(plhs[0])!=1)
mexErrMsgTxt("Error..Image Euclidean Distance must be a scalar.");
/* check that number of rows in input arguments is 1 */
if(mxGetM(prhs[1])!=1 || mxGetM(prhs[2])!=1)
mexErrMsgTxt("Error..Inputs must be row vectors.");
/* Get the value of r */
r = mxGetScalar(prhs[0]);
/* Getting the input vectors */
Ip = mxGetPr(prhs[1]);
Is = mxGetPr(prhs[2]);
ncols = mxGetN(prhs[1]);
/* Creating link for the scalar output */
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
dist = mxGetPr(plhs[0]);
imedDistCal(r,Ip,Is,(mwSize)ncols,dist);
}
1 回答
正如上面的评论所述,MATLAB崩溃是因为
mxWhateverFunction(plhs[0]) <-- fill in for whatever
在测试之前没有链接到任何变量时导致地址无效 .下面这段代码
应该在以下之后移动以避免此问题 .