在app中显示std :: cout

时间:2016-03-28 16:15:32

标签: c++ ios xcode cout

我在我的程序中进行了大量的调试监控,因此每当出现不需要的内容时,XCode中会出现一条消息,其中包含" std :: cout"显示发生了什么,发生了什么,等等。 当我在连接到我的电脑的iPhone或iPad上测试应用程序时,这也很有效(因为我一直打开XCode来显示错误)。

但是现在我在几个beta测试者的设备上安装了应用程序,他们没有看到这些消息...... 重写代码以路由所有" cout"一个字符串会花费很多时间,因为它们出现在几个类和子类等的所有地方......

是否可以简单地读出输出控制台的最后一行或检测写入控制台的事件,然后将其复制到一个单独的字符串?

1 个答案:

答案 0 :(得分:0)

这是我在一些 android 项目上所做的将 stdout 和 stderr 转发到 logcat 的事情。您可以使用相同的方法将 stdout/stderr 转发到您想要的任何地方:

struct stream {
   const char *name;
   int fd[2];
   FILE *src;
};

static void*
log_thread(void *arg)
{
   struct stream *stream = arg;
   char buf[4000], *off = buf, *nl; // Can't be too big or android stops logging
   for (ssize_t r = 0;;off += r, r = 0) {
      if (off - buf < sizeof(buf) - 1) {
         errno = 0;
         r = read(stream->fd[0], off, (sizeof(buf) - 1) - (off - buf));
         if (r <= 0) { if (errno == EINTR) continue; else break; }
         off[r] = 0;
      }
      if ((nl = strrchr(off, '\n'))) {
         *nl = 0; ++nl;
         __android_log_write(ANDROID_LOG_INFO, stream->name, buf);
         r = (off + r) - nl;
         memcpy((off = buf), nl, r);
      } else if (off - buf >= sizeof(buf)) {
         __android_log_write(ANDROID_LOG_INFO, stream->name, buf);
         r = 0; off = buf;
      }
   }
   close(stream->fd[0]);
   close(stream->fd[1]);
   return NULL;
}

__attribute__((constructor)) static void
log_init(void) {
   static struct stream stream[] = { { .name = "stdout" }, { .name = "stderr" } };
   stream[0].src = stdout; stream[1].src = stderr;
   for (size_t i = 0; i < sizeof(stream) / sizeof(stream[0]); ++i) {
      setvbuf(stream[i].src, NULL, _IOLBF, BUFSIZ);
      pipe(stream[i].fd);
      dup2(stream[i].fd[1], fileno(stream[i].src));
      pthread_t thread;
      pthread_create(&thread, 0, log_thread, &stream[i]);
      pthread_detach(thread);
   }
}