【问题标题】:String passing to formatting function?字符串传递给格式化函数?
【发布时间】:2012-06-25 11:56:52
【问题描述】:

打印到标准错误的原始代码:

extern "C" {
/* error: output error message */
void Error(const int error, char *message, ...)
{
    va_list arg;
   fflush(stdout);
   fflush(stderr);

   if (error > 0)
     fprintf(stderr, "\nError: ");
   else
     fprintf(stderr, "\nWarning: ");

   va_start(arg, message);
   vfprintf(stderr, message, arg);
   va_end(arg);

   fflush(stderr);
   if (error > 0)
      exit(error);
}

void main(){
Error(0,"Problem %s in file", "sometext");
}

}//extern "C"

我修改了我的代码,使其看起来像这样。它应该打印到 logcat

extern "C" {
#include <android/log.h>
#include <jni.h>
#include <sys/types.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>

/* error: output error message */
void Error(const int error, char *message, ...)
{
    va_list arg;

   va_start(arg, message);
   if (error > 0)
   __android_log_print(ANDROID_LOG_ERROR, "HTS_API", message, arg);
      else
   __android_log_print(ANDROID_LOG_WARN, "HTS_API", message, arg);
   va_end(arg);

   if (error > 0)
      exit(error);
}
void main(){
Error(0,"Problem %s in file", "sometext");
}

}//extern "C"

问题是我的代码输出:'Problem |�;A.|�;A. in file'

和__android_log_print(ANDROID_LOG_WARN, "HTS_API","Problem %s in file", "sometext");

正确的输出是:'Problem sometext in file'

我做错了什么?

【问题讨论】:

  • 您将其定义为Error,但将其称为error。另外,它应该是int main。
  • 这是一个错字,main 只是一个随机函数
  • 您是否收到任何编译器警告?

标签: android c string logcat android-ndk


【解决方案1】:

__android_log_print 不接受 va_list 作为参数。它接受可变参数列表。

看起来像是在他们添加的最新 NDK 中

int __android_log_vprint(int prio, const char *tag, const char *fmt, va_list ap);

这就是你想要的。以前,您必须通过将Error 重新实现为带有可变参数列表的宏,或使用vsprintf 在缓冲区中格式化错误消息然后说来解决此问题

__android_log_print(ANDROID_LOG_WARN, "HTS_API", "%s", buf);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    相关资源
    最近更新 更多