I am writing a JNI. In that, my Java program takes an Image byte array using ByteOutputStream() and then this array is used to call a function in C that converts byte array to unsigned char*. Here is the code:
JNIEXPORT void JNICALL Java_ImageConversion_covertBytes(JNIEnv *env, jobject obj, jbyteArray array)
{
unsigned char* flag = (*env)->GetByteArrayElements(env, array, NULL);
jsize size = (*env)->GetArrayLength(env, array);
for(int i = 0; i < size; i++) {
printf("%c", flag[i]);}
}
In this I keep getting a warning when I compile:
warning: initializing 'unsigned char *' with an expression of type 'jbyte *' (aka 'signed char *') converts between pointers to integer types with different sign [-Wpointer-sign]
unsigned char* flag = (*env)->GetByteArrayElements(env, array, NULL);
How can I remove this warning? I want to print the all characters.
The warning exists because the sign change might be important. In JNI the jbyte
corresponds to Java byte
which is a signed 8-bit integer; in C it is explicitly signed char
.
However, it is OK to access any object with any character pointer, so you can cast to unsigned char
explicitly:
unsigned char* flag = (unsigned char*)(*env)->GetByteArrayElements(env, array, NULL);
Alternatively, you can declare flag
as signed char
:
signed char* flag = (*env)->GetByteArrayElements(env, array, NULL);
This is fine for printf("%c\\n", flag[i]);
because %c
requires that the argument be an integer; the integer is then converted to unsigned char
so both signed
and unsigned char
will do.
However 3rd option would be to use neither - if you just want to write them to the terminal, use a void *
pointer and fwrite
:
JNIEXPORT void JNICALL
Java_ImageConversion_covertBytes(JNIEnv *env, jobject obj, jbyteArray array)
{
void *flag = (*env)->GetByteArrayElements(env, array, NULL);
jsize size = (*env)->GetArrayLength(env, array);
fwrite(flag, 1, size, stdout);
}
and let fwrite
worry about the looping.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.