在 Android 原生 ndk 中记录变量的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12159316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:55:42  来源:igfitidea点击:

Logging values of variables in Android native ndk

androidc++debuggingloggingandroid-ndk

提问by dorien

I set up logging with C++in Android NDK.

我在 Android NDK 中使用C++设置日志记录。

I can print a message to logcat like this:

我可以像这样向 logcat 打印一条消息:

__android_log_write(ANDROID_LOG_INFO, "tag here", "message here");

Now let's say I have an integer called testint. How can I print the value of this int?

现在假设我有一个名为testint的整数。如何打印此 int 的值?

Something like this prints the address, but I want the value. I haven't found anything in C++on how to do this. Thanks for any help!

像这样的东西会打印地址,但我想要这个值。我还没有在C++ 中找到任何关于如何做到这一点的内容。谢谢你的帮助!

__android_log_print(ANDROID_LOG_INFO, "sometag", "%p", *test);

采纳答案by Benoit Duffez

You could use __android_log_printwhich uses a sprintf-like syntax that formats your data into a string.

您可以使用__android_log_printwhich 使用类似sprintf语法将您的数据格式化为字符串。

__android_log_print(ANDROID_LOG_INFO, "sometag", "test int = %d", testInt);

回答by Adam

Here's the most concise way I've seen:

这是我见过的最简洁的方法:

#include <android/log.h>

#define  LOG_TAG    "someTag"

#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#define  LOGW(...)  __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)

...

// Now you can log very simply like this:
int foo = 42;
LOGD( "This is a number from JNI: %d", foo );

Also, make sure you link to the log library in your Android.mk:

另外,请确保您链接到 Android.mk 中的日志库:

LOCAL_LDLIBS    := -llog

回答by mah

Take advantage of the variadic log print function you have available. For my own code, I provide a LogInfo() function to make it simple. Of course there are several options available to you here.

利用您可用的可变日志打印功能。对于我自己的代码,我提供了一个 LogInfo() 函数来简化它。当然,这里有多种选择可供您选择。

void LogInfo(const char *sTag, const char *fmt, ...)
{
  va_list ap;
  va_start(ap, fmt);
  __android_log_vprint(ANDROID_LOG_INFO, sTag, fmt, ap);
  va_end(ap);
}

回答by kelnos

__android_log_print() takes a format string and a variable argument list. The format specifier you're looking for to print out a signed integer is "%d". So something like this is what you want:

__android_log_print() 采用格式字符串和可变参数列表。您要查找的用于打印有符号整数的格式说明符是“%d”。所以这样的事情就是你想要的:

int foo = 42;
__android_log_print(ANDROID_LOG_INFO, "SomeTag", "foo is %d", foo);

For more information on format strings, you can see the sprintf manual.

有关格式字符串的更多信息,您可以查看sprintf 手册