In mex files, where does output to stdout and stderr go?

67 ビュー (過去 30 日間)
Oliver Woodford
Oliver Woodford 2014 年 6 月 5 日
コメント済み: A King 2020 年 4 月 3 日
If I link an external library to a mex file, and this library sends text output to stdout or stderr, what does MATLAB do with this output? Is there any way of saving it?

回答 (3 件)

Oliver Woodford
Oliver Woodford 2015 年 5 月 12 日
編集済み: Oliver Woodford 2015 年 5 月 12 日
In a C++ mex file you can output std::cout to the command line, by putting the following code somewhere in your mex file:
class mystream : public std::streambuf
{
protected:
virtual std::streamsize xsputn(const char *s, std::streamsize n) { mexPrintf("%.*s", n, s); return n; }
virtual int overflow(int c=EOF) { if (c != EOF) { mexPrintf("%.1s", &c); } return 1; }
};
class scoped_redirect_cout
{
public:
scoped_redirect_cout() { old_buf = std::cout.rdbuf(); std::cout.rdbuf(&mout); }
~scoped_redirect_cout() { std::cout.rdbuf(old_buf); }
private:
mystream mout;
std::streambuf *old_buf;
};
static scoped_redirect_cout mycout_redirect;
  1 件のコメント
Oliver Woodford
Oliver Woodford 2015 年 5 月 12 日
This will actually redirect output to std::out in all other mex files too, until the original mex file is cleared. To avoid this, you can place this:
scoped_redirect_cout mycout_redirect;
at the top of the mex function, and remove the line:
static scoped_redirect_cout mycout_redirect;
from the mex file. However, this approach carries an overhead per mex call.

サインインしてコメントする。


Andrew Stevens
Andrew Stevens 2018 年 2 月 11 日
編集済み: Andrew Stevens 2018 年 2 月 11 日
Additionally to Olivers solution:
  • In R2016 under Linux it would seem that mexPrintf itself uses iostream (internally). You have to switch the stream buffer back to the original for the mexPrintf call to avoid a stack overflow.
  • In R2016 under Linux at least mexPrintf appears to check the thread from which it is being called (presumably because mx/mex API is not thread safe). If the calling stack is not the same as that used to enter mexFunction it merely logs "Error writing to output stream". The test (or is it a breakage?) alas is rather conservative: it triggers even if the "thread" is actually just a lightweight coroutine library like quickthreads is being used (e.g. SystemC).
The work-around is to buffer the output in the custom streambuf and flush only from the calling thread.

Tianyang Li
Tianyang Li 2015 年 1 月 6 日
If you start maltab using -nojvm then stdout and stderr are visible.
  1 件のコメント
A King
A King 2020 年 4 月 3 日
This is the solution. Thanks for sharing.

サインインしてコメントする。

製品

Community Treasure Hunt

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

Start Hunting!

Translated by