Assertion in MEX file causes Matlab to crash

你。 提交于 2019-12-07 17:45:44

问题


I'm using the mxAssert-macro defined by matrix.h in my C++ code which mex perfectly compiles. When an assertion is violated in my called mex code, this assertion causes not my program to crash but Matlab itself. Am I missing something out? Is that intended behavior? When I look at Matlab's crash report, the causing assertion is the very same raised by my code - including my descriptive description... Do I have to run my mex code in a certain way so that Matlab can recognize mex code caused assertions (similar to try-catch)? Probably there's another way to safely stop my mex code and return to the Matlab prompt.

Thank you in advance, any help is very appreciated!

EDIT: the code is compiled with the command mex -v Temp.cpp -g

EDIT: a minimal example that brings my matlab to its knees:

#include <matrix.h>
class Temp {
public:
    Temp();
    virtual ~Temp();
};

Temp::Temp() {
    // TODO Auto-generated constructor stub
}

Temp::~Temp() {
    // TODO Auto-generated destructor stub
}

extern "C" {
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int foo = 10;
    mxAssert(foo==11, "foo is not 10");
}
}

回答1:


On my system (Ubuntu 64), it crashes too.

I guess it makes senss, because that's what assert is supposed to do.

I strongly advise you to use something like:

if(error){mexErrMsgTxt("assert failed\n");}

Otherwise, one of my friends have the following trick (with preprocessor instructions):

#define assert( isOK )       ( (isOK) ? (void)0 : (void) mexErrMsgTxt("assert failed\n") )

To print individual error strings, e.g. myassert(A=B,"A not B") , you can enhance this a little bit:

#define myassert( isOK,astr )      ( (isOK) ? (void)0 : (void) mexErrMsgTxt(astr) ) 

He also told me that you can improvie it using something like:

#isOK,__LINE__,__PRETTY_FUNCTION__, __FILE__

...in order to print the line number and so on.



来源:https://stackoverflow.com/questions/8492761/assertion-in-mex-file-causes-matlab-to-crash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!