How to print C-preprocessor variables like __LINE__ with mexErrMsgTxt() In Matlab MEX

你离开我真会死。 提交于 2019-12-06 16:39:22

Concatenating preprocessor tokens works as long as you only use __FILE__, __LINE__ and a string literal as message. Then you can write something like

#define STRINGIZE_I(x) #x
#define STRINGIZE(x) STRINGIZE_I(x)

#define myassert(isOK, astr) ( (isOK) ? (void)0 : (void) mexErrMsgTxt(__FILE__ ":" STRINGIZE(__LINE__) ": " astr) )

Unfortunately, __PRETTY_FUNCTION__ is not a string literal even for those compilers who support it. If you want to use it (or less fixed error messages), you'll have to assemble the string dynamically, which means something along the lines of

#define myassert(isOK, astr)                                            \
  do {                                                                  \
    if(!(isOk)) {                                                       \
      std::ostringstream fmt;                                           \
      fmt << "In " << __PRETTY_FUNCTION__ << ", "                       \
          << __FILE__ << ":" << __LINE__ << ": " << (astr);             \
      (void) mexErrMsgTxt(fmt.str().c_str());                           \
    }                                                                   \
  } while(false)

For C, do the same with snprintf. (Or asprintf. It avoids problems with fixed buffer lengths and long error messages, and it is about as portable as __PRETTY_FUNCTION__). Either way, roughly like

#define myassert(isOK, astr)                                            \
  do {                                                                  \
    if(!(isOk)) {                                                       \
      char buf[ENOUGH_SPACE];                                           \
      snprintf(buf, ENOUGH_SPACE, "In %s, %s:%d: %s",                   \
               __PRETTY_FUNCTION__, __FILE__, __LINE__, (astr));        \
      buf[ENOUGH_SPACE - 1] = '\0';                                     \
      (void) mexErrMsgTxt(buf);                                         \
    }                                                                   \
  } while(0)

...where ENOUGH_SPACE would have to be defined appropriately (in the snprintf case).

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