Android NDK重定向std::cout输出到log
16lz
2021-01-23
第一步,继承std::streambuf
#include <iostream>#include <streambuf>class MyStreamBuf : public std::streambuf{enum{BUFFER_SIZE = 255,};public:MyStreamBuf(){buffer_[BUFFER_SIZE] = '\0';setp(buffer_, buffer_ + BUFFER_SIZE - 1);}~MyStreamBuf(){sync();}protected:virtual int_type overflow(int_type c){if (c != EOF){*pptr() = c;pbump(1);}flush_buffer();return c;}virtual int sync(){flush_buffer();return 0;}private:int flush_buffer(){int len = int(pptr() - pbase());if (len <= 0)return 0;if (len <= BUFFER_SIZE)buffer_[len] = '\0';#ifdef ANDROID android_LogPriority t = ANDROID_LOG_INFO;__android_log_write(t, "mylog", buffer_);#else printf("%s", buffer_);#endif pbump(-len);return len;}private:char buffer_[BUFFER_SIZE + 1];};
第二步,创建MyStreamBuf对象,并指定给std::cout
MyStreamBuf g_MyStreamBuf;std::cout.rdbuf(&g_MyStreamBuf);//NOTE: std::endl会立即调用sync方法将缓冲区字符写入log,并不只是换行用std::cout << "hello " << 123 << std::endl;std::cout << "pi = " << 3.14 << std::endl;
这样,就可以是Eclipse的LogCat查看std::cout输出了。
更多相关文章
- android非法字符的判定、表情符号的判定
- Android将获取到文件的uri转换为字符串的路径
- android XML文件常用字符转义
- Android 创建一个包含星期的格式字符串
- Android源码快速查找文件、搜索字符串和编译
- android上传图片以及POST字符串
- 通过OpenGL ES混合模式缩放视频缓冲区-Android 4游戏编程高级篇
- android调用webservice方法,参数和返回值都用字符串
- android 发送短信 判断号码规则 判断字符数70