在使用Jni的JNIEnv->NewStringUTF的時候拋出了異常"JNI DETECTED ERROR IN APPLICATION: input is not valid Modified UTF-8: illegal start byte 0xfe
"。網上搜索了一下,這個異常是因爲Java虛擬機內部的dalvik/vm/CheckJni.c
中的checkUtfString
函數拋出的,而且JVM的這個接口明確是不支持四個字節的UTF8字符。所以須要在調用函數以前,對接口傳入的字符串進行過濾,過濾函數以下:html
int checkUtfString(const char* bytes) { const char* origBytes = bytes; if (bytes == NULL) { return -1; } while (*bytes != '\0') { unsigned char utf8 = *(bytes++); // Switch on the high four bits. switch (utf8 >> 4) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: { // Bit pattern 0xxx. No need for any extra bytes. break; } case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0f: { /*printf("****JNI WARNING: illegal start byte 0x%x\n", utf8);*/ return -1; } case 0x0e: { // Bit pattern 1110, so there are two additional bytes. utf8 = *(bytes++); if ((utf8 & 0xc0) != 0x80) { /*printf("****JNI WARNING: illegal continuation byte 0x%x\n", utf8);*/ return -1; } // Fall through to take care of the final byte. } case 0x0c: case 0x0d: { // Bit pattern 110x, so there is one additional byte. utf8 = *(bytes++); if ((utf8 & 0xc0) != 0x80) { /*printf("****JNI WARNING: illegal continuation byte 0x%x\n", utf8);*/ return -1; } break; } } } return 0; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
int checkUtfString(const char* bytes)
{
const char* origBytes = bytes;
if (bytes == NULL) {
return -1;
}
while (*bytes != '\0') {
unsigned char utf8 = *(bytes++);
// Switch on the high four bits.
switch (utf8 >> 4) {
case 0x00:
case 0x01:
case 0x02:
case 0x03:
case 0x04:
case 0x05:
case 0x06:
case 0x07: {
// Bit pattern 0xxx. No need for any extra bytes.
break;
}
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0f: {
/*printf("****JNI WARNING: illegal start byte 0x%x\n", utf8);*/
return -1;
}
case 0x0e: {
// Bit pattern 1110, so there are two additional bytes.
utf8 = *(bytes++);
if ((utf8 & 0xc0) != 0x80) {
/*printf("****JNI WARNING: illegal continuation byte 0x%x\n", utf8);*/
return -1;
}
// Fall through to take care of the final byte.
}
case 0x0c:
case 0x0d: {
// Bit pattern 110x, so there is one additional byte.
utf8 = *(bytes++);
if ((utf8 & 0xc0) != 0x80) {
/*printf("****JNI WARNING: illegal continuation byte 0x%x\n", utf8);*/
return -1;
}
break;
}
}
}
return 0;
}
|
參考連接 android jni中 utf-8的checkjava