JNI:打印Matrix到logcat不起作用

时间:2015-07-22 07:54:23

标签: android c++ matrix java-native-interface logcat

我一直在尝试使用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:    ]

如何显示矩阵内的内容?

1 个答案:

答案 0 :(得分:1)

您的问题出现在以下代码行中:

__android_log_write(ANDROID_LOG_INFO , "Matrix: ", (char*)&v);

(char*)&vfloatv)的字节模式重新解释为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]);