JNI: Print Matrix for logcat not working
I am trying to output a matrix via logcat when using C ++ and JNI. I'm completely new to this stuff, so after some research I tried it with the following code:
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);
}
}
but this approach just gives me:
07-22 09:21:56.517 14487-14582/name.example I/Matrix:๏น [ 07-22 09:21:56.517 14487:14582 I/Matrix: ]
How can I show what's inside the matrix?
source to share
Your problem is with the following line of code:
__android_log_write(ANDROID_LOG_INFO , "Matrix: ", (char*)&v);
(char*)&v
reinterprets the byte pattern float
( v
) as a C string, which doesn't work (and is also sometimes allowed). Instead, to convert float
to a string, use sprintf
either snprintf
or, if possible std::to_string
(this requires C ++ 11):
char str[buffer_size];
snprintf(str, buffer_size, "%f", Matrix[i][j]);
__android_log_write(ANDROID_LOG_INFO, "Matrix: ", str);
or
__android_log_write(ANDROID_LOG_INFO, "Matrix: ", std::to_string(Matrix[i][j]).c_str());
As pointed out in the comments, there is also __android_log_print
one that already integrates the syntax printf
:
__android_log_print(ANDROID_LOG_INFO, "Matrix: ", "%f", Matrix[i][j]);
source to share