JNI:将矩阵打印到 logcat 不起作用

JNI: Printing Matrix to logcat doesn't work

我一直试图在使用 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*)&vfloat (v) 的字节模式重新解释为 C 字符串,这是行不通的(也只是偶尔允许)。相反,要将 float 转换为字符串,请使用 sprintfsnprintf 或者,如果可能,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]);