在MATLAB mex文件中正确重载一个stringbuf来替换cout [英] Correctly over-loading a stringbuf to replace cout in a MATLAB mex file
问题描述
MathWorks目前不允许您在MATLAB桌面打开时使用来自mex文件的cout,因为它们已重定向stdout。他们目前的解决方法是提供 mexPrintf,他们要求您改用的功能。在googling一点后,我认为可以扩展std :: stringbuf类来做我需要的。这是我到目前为止。这是足够健壮,还是有其他方法我需要重载或更好的方法来做到这一点? (在普通UNIX环境中寻找可移植性,并且如果这个代码没有链接到一个mex可执行文件,那么可以正常使用std :: cout)
MathWorks currently doesn't allow you to use cout from a mex file when the MATLAB desktop is open because they have redirected stdout. Their current workaround is providing a function, mexPrintf, that they request you use instead. After googling around a bit, I think that it's possible to extend the std::stringbuf class to do what I need. Here's what I have so far. Is this robust enough, or are there other methods I need to overload or a better way to do this? (Looking for portability in a general UNIX environment and the ability to use std::cout as normal if this code is not linked against a mex executable)
class mstream : public stringbuf {
public:
virtual streamsize xsputn(const char *s, std::streamsize n)
{
mexPrintf("*s",s,n);
return basic_streambuf<char, std::char_traits<char>>::xsputn(s,n);
}
};
mstream mout;
outbuf = cout.rdbuf(mout.rdbuf());
推荐答案
你真的不想重载std :: stringbuf,你想重载std :: streambuf或std :: basic_streambuf(如果你想支持多个字符类型),你也需要重写溢出方法。
You don't really want to overload std::stringbuf, you want to overload std::streambuf or std::basic_streambuf (if you want to support multiple character types), also you need to override the overflow method as well.
但我也认为你需要重新思考你的解决方案你的问题。
But I also think you need to rethink your solution to your problem.
cout只是一个ostream,所以如果所有的类/函数都需要一个ostream,那么你可以传递在任何你喜欢的。例如cout,ofstream等等
cout is just a ostream, so if all classes / functions takes a ostream then you can pass in anything you like. e.g. cout, ofstream, etc
如果这太难了,我会创建自己的cout版本,也许叫mycout,可以在编译器时间或运行时间定义
If that's too hard then I would create my own version of cout, maybe called mycout that can be defined at either compiler time or runtime time (depending on what you want to do).
一个简单的解决方案可能是:
A simple solution may be:
#include <streambuf>
#include <ostream>
class mystream : public std::streambuf
{
public:
mystream() {}
protected:
virtual int_type overflow(int_type c)
{
if(c != EOF)
{
char z = c;
mexPrintf("%c",c);
return EOF;
}
return c;
}
virtual std::streamsize xsputn(const char* s, std::streamsize num)
{
mexPrintf("*s",s,n);
return num;
}
};
class myostream : public std::ostream
{
protected:
mystream buf;
public:
myostream() : std::ostream(&buf) {}
};
myostream mycout;
cout版本可以是:
And the cout version could just be:
typedef std::cout mycout;
运行时版本有点多,但很容易做。
A runtime version is a bit more work but easily doable.
这篇关于在MATLAB mex文件中正确重载一个stringbuf来替换cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!