[size=large]在matlab、C++混合编程的时候,可能会用到之前的代码。代码中会有许多的输出(使用std::cout);
如果将这些std::cout重新用mexPrintf()写一遍,不仅费时费力,还造成原来的程序在别的地方无法编译的问题。
那么,有没有办法将std::cout重定向到mexPrintf呢?
原理没深究,直接[color=red]转载[/color]代码:[/size][url]http://stackoverflow.com/questions/243696/correctly-over-loading-a-stringbuf-to-replace-cout-in-a-matlab-mex-file[/url]
[color=blue][size=large]先定义一个自己的streambuf类:[/size][/color]
[color=blue][size=large]mexFunction中这么用就可以了:[/size][/color]
如果将这些std::cout重新用mexPrintf()写一遍,不仅费时费力,还造成原来的程序在别的地方无法编译的问题。
那么,有没有办法将std::cout重定向到mexPrintf呢?
原理没深究,直接[color=red]转载[/color]代码:[/size][url]http://stackoverflow.com/questions/243696/correctly-over-loading-a-stringbuf-to-replace-cout-in-a-matlab-mex-file[/url]
[color=blue][size=large]先定义一个自己的streambuf类:[/size][/color]
class mstream : public std::streambuf {
public:
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;
}
};
[color=blue][size=large]mexFunction中这么用就可以了:[/size][/color]
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
mstream mout;
std::streambuf *outbuf = std::cout.rdbuf (&mout);//重定向cout
std::cout << "haha" << std::endl;
std::cout.rdbuf (outbuf);//结束重定向
}