You can create a class derived from std::streambuf that uses special Android functions to send the generated character sequence. However, I don't know where, by default, the std::cout implementation sends characters to Android. Basically, it will look something like this:
class androidbuf : public std::streambuf { public: enum { bufsize = 128 }; // ... or some other suitable buffer size androidbuf() { this->setp(buffer, buffer + bufsize - 1); } private: int overflow(int c) { if (c == traits_type::eof()) { *this->pptr() = traits_type::to_char_type(c); this->sbumpc(); } return this->sync()? traits_type::eof(): traits_type::not_eof(c); } int sync() { int rc = 0; if (this->pbase() != this->pptr()) { char writebuf[bufsize+1]; memcpy(writebuf, this->pbase(), this->pptr() - this->pbase()); writebuf[this->pptr() - this->pbase()] = '\0'; rc = __android_log_write(ANDROID_LOG_INFO, "std", writebuf) > 0; this->setp(buffer, buffer + bufsize - 1); } return rc; } char buffer[bufsize]; };
To actually configure std::cout to write to this stream buffer, you would do something similar in your main() function:
int main() { std::cout.rdbuf(new androidbuf); ... }
This creates a memory leak for a single androidbuf stream, which, however, is somewhat deliberate: the stream can be written after main() completed, and it is cleared when std::cout destroyed. If you do not want this, you can restore the original stream buffer std::cout or set it to null and remove the return from rdbuf() :
Dietmar Kühl Jan 15 '12 at 14:13 2012-01-15 14:13
source share