Assertion in MEX file causes Matlab to crash

2019-05-12 00: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条回答
走好不送
2楼-- · 2019-05-12 01:21

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.

查看更多
登录 后发表回答