std::cout 輸出到android log系統裏

android重定向cout,使用cout來打印日誌:https://blog.csdn.net/lj402159806/article/details/78252984

android_buf.h:
 

#include <iostream>
#include <streambuf>
#include <android/log.h>


class AndroidBuf : public std::streambuf {
    enum {
        BUFFER_SIZE = 255,
    };

public:
    AndroidBuf();

    ~AndroidBuf();

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();

private:
    char buffer_[BUFFER_SIZE + 1];
};

 

android_buf.cpp:
 

#include "android_buf.h"

AndroidBuf::AndroidBuf() {
    buffer_[BUFFER_SIZE] = '\0';
    setp(buffer_, buffer_ + BUFFER_SIZE - 1);
}

AndroidBuf::~AndroidBuf() {
    sync();
}

int AndroidBuf::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, "Native", buffer_);
#else
    printf("%s", buffer_);
#endif

    pbump(-len);
    return len;
}

 

指定給std::cout
 

#include "android_buf.h"
int main() {
std::cout.rdbuf(new AndroidBuf);

//NOTE: std::endl會立即調用sync方法將緩衝區字符寫入log,並不只是換行用
std::cout << "hello " << 123 << std::endl;
}

使用完記得釋放引用
 

delete std::cout.rdbuf(0);

 

發佈了108 篇原創文章 · 獲贊 29 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章