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

JNI: Printing Matrix to logcat doesn't work

本文关键字:logcat 不起作用 打印 JNI      更新时间:2023-10-16

我一直在尝试通过logcat给出一个矩阵,而使用c++和JNI。我对这些东西完全陌生,所以经过一些研究,我用以下代码尝试了它:

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]);