`

matlab的mexFunction中使用std::cout(部分转载)

阅读更多
在matlab、C++混合编程的时候,可能会用到之前的代码。代码中会有许多的输出(使用std::cout);
如果将这些std::cout重新用mexPrintf()写一遍,不仅费时费力,还造成原来的程序在别的地方无法编译的问题。

那么,有没有办法将std::cout重定向到mexPrintf呢?

原理没深究,直接转载代码:
http://stackoverflow.com/questions/243696/correctly-over-loading-a-stringbuf-to-replace-cout-in-a-matlab-mex-file
先定义一个自己的streambuf类:
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;
    }
};

mexFunction中这么用就可以了:
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);//结束重定向

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics