English 中文(简体)
Is “std:cout” weable in Anders-ndk
原标题:Is "std::cout" usable in Android-ndk

In Android-ndk, we could use "__android_log_write", "__android_log_print", ... etc to output messages to the "LogCat" window. How about if I use "std::cout" to output some strings ? E.g.

std::cout << "some strings" << std::endl;

Where would the strings be sent.

It seems that Android does not have Console Applications and the above strings may not be sent. Could I redirect the "stdout" to a file so that sending strings to "std::cout" is equivalent to logging messages ?

最佳回答

According to the Android documentation, stdout & stderr output to /dev/null. You can use the Android Debug Bridge to achieve what you want.

By default, the Android system sends stdout and stderr (System.out and System.err) output to /dev/null. In processes that run the Dalvik VM, you can have the system write a copy of the output to the log file. In this case, the system writes the messages to the log using the log tags stdout and stderr, both with priority I. To route the output in this way, you stop a running emulator/device instance and then use the shell command setprop to enable the redirection of output. Here s how you do it:

$ adb shell stop
$ adb shell setprop log.redirect-stdio true
$ adb shell start

The system retains this setting until you terminate the emulator/device instance. To use the setting as a default on the emulator/device instance, you can add an entry to /data/local.prop on the device.

问题回答

您可以创建从<代码>std:streambuf <>/code>中得出的一个类别,该类组利用安特的功能发送生成的特性序列。 然而,我不知道“<代码>的未履约情况:<>/编码>在何地发送了安康的特性。 从根本上说,这将看上去:

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

            rc = __android_log_write(ANDROID_LOG_INFO, "std", writebuf) > 0;
            this->setp(buffer, buffer + bufsize - 1);
        }
        return rc;
    }

    char buffer[bufsize];
};

为了实际建立<代码>std:cout,以写到这一流层缓冲,你将在<代码>main()功能中做类似的事情:

int main() {
    std::cout.rdbuf(new androidbuf);
    ...
}

这对一个<代码>androidbuf造成记忆泄露。 然而,这几类是有意的:流体可在<代码>main(>后书写,并在<代码>上下:cout被销毁时流出。 如果你不希望这样做,你可以恢复<代码>:cout。 s 原始流缓冲,或使之无效并删除rdbuf ():

   // avoid a one-time resource leak but don t get output afterwards:
   delete std::cout.rdbuf(0);

另一种选择:

#include <sstream>

class MyStream
{
private:
   std::stringstream m_ss;
   int m_logLevel;
public:

   MyStream(int Xi_logLevel)
   {
      m_logLevel = Xi_logLevel;
   };
   ~MyStream()
   {
      __android_log_print(m_logLevel,LOG_TAG,"%s", m_ss.str().c_str());
   }

   template<typename T> MyStream& operator<<(T const& Xi_val)
   {
      m_ss << Xi_val;
      return *this;
   }
};

#define MY_LOG(LOG_LEVEL) MyStream(ANDROID_LOG_##LOG_LEVEL) << __FUNCTION__ << ":" << __LINE__ << " : "

<>PROS:

(1) 短信立即印发。

www.un.org/Depts/DGACM/index_french.htm

(1) 您必须修改其法典(原文:cout->MY_LOG(X))。

(2) 每一部印本都制成物体并销毁。

(*** This answer base on this answer)

Dietmar Kühl的回答非常好,但它没有发挥促进作用。 https://www.crystax.net/“rel=“nofollow” Crystax NDK。 我发现another concept,并稍作修改。 该守则是:

#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <android/log.h>

static int pfd[2];
static pthread_t thr;
static const char *tag = "myapp";

static void *thread_func(void*)
{
    ssize_t rdsz;
    char buf[128];
    while((rdsz = read(pfd[0], buf, sizeof buf - 1)) > 0) {
        if(buf[rdsz - 1] ==  
 ) --rdsz;
        buf[rdsz] = 0;  /* add null-terminator */
        __android_log_write(ANDROID_LOG_DEBUG, tag, buf);
    }
    return 0;
}

int start_logger(const char *app_name)
{
    tag = app_name;

    /* make stdout line-buffered and stderr unbuffered */
    setvbuf(stdout, 0, _IOLBF, 0);
    setvbuf(stderr, 0, _IONBF, 0);

    /* create the pipe and redirect stdout and stderr */
    pipe(pfd);
    dup2(pfd[1], 1);
    dup2(pfd[1], 2);

    /* spawn the logging thread */
    if(pthread_create(&thr, 0, thread_func, 0) == -1)
        return -1;
    pthread_detach(thr);
    return 0;
}

And its use:

...
start_logger("MyApp");
...

现在,所有产出都来自增长。 log: cer子将:

#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/logger.hpp>

...
boost::log::add_console_log(std::cout);
boost::log::add_common_attributes();

boost::log::sources::logger_mt lg;
BOOST_LOG(lg) << "Hello, World!";
...

简便打印工作记录和目录。

步骤1:在你的共同负责人档案中增加以下内容。

#include <android/log.h>
    
#define LOGV(TAG, ...) __android_log_print(ANDROID_LOG_VERBOSE, TAG,__VA_ARGS__)
#define LOGD(TAG, ...) __android_log_print(ANDROID_LOG_DEBUG  , TAG,__VA_ARGS__)
#define LOGI(TAG, ...) __android_log_print(ANDROID_LOG_INFO   , TAG,__VA_ARGS__)
#define LOGW(TAG, ...) __android_log_print(ANDROID_LOG_WARN   , TAG,__VA_ARGS__)
#define LOGE(TAG, ...) __android_log_print(ANDROID_LOG_ERROR  , TAG,__VA_ARGS__)

Step 2: Now just call

LOGV("MYTAGNAME", "Hello!!");
LOGD("MYTAGNAME", "Hello!!");
LOGI("MYTAGNAME", "Hello!!");
LOGW("MYTAGNAME", "Hello!!");
LOGE("MYTAGNAME", "Hello!!");

Step 3: you can see logs in logcat as below.

“在此处的影像描述”/</a





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签