在使用 C++ 和 JNI 时,我一直在尝试通过 logcat 给出一个矩阵。我对这些东西完全陌生,所以经过一些研究后,我尝试使用以下代码:
for(int i = 0; i<4; i++){
for (int j = 0;j<4; j++){
float v = Matrix[i][j];
__android_log_write(ANDROID_LOG_INFO , "Matrix: ", (char*)&v);
}
}
但这种方法只是给了我:
07-22 09:21:56.517 14487-14582/name.example I/Matrix:﹕ [ 07-22 09:21:56.517 14487:14582 I/Matrix: ]
如何显示矩阵中的内容?
最佳答案
您的问题出在以下代码行中:
__android_log_write(ANDROID_LOG_INFO , "Matrix: ", (char*)&v);
(char*)&v
将 float
(v
) 的字节模式重新解释为 C 字符串,这不起作用 (并且也只是偶尔被允许)。相反,要将 float
转换为字符串,请使用 sprintf
或 snprintf
或者,如果可能,使用 std::to_string
(这需要 C++11):
char str[buffer_size];
snprintf(str, buffer_size, "%f", Matrix[i][j]);
__android_log_write(ANDROID_LOG_INFO, "Matrix: ", str);
或
__android_log_write(ANDROID_LOG_INFO, "Matrix: ", std::to_string(Matrix[i][j]).c_str());
正如评论中指出的,还有 __android_log_print
,它已经集成了 printf
语法:
__android_log_print(ANDROID_LOG_INFO, "Matrix: ", "%f", Matrix[i][j]);
关于android - JNI : Printing Matrix to logcat doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31557098/