JNI函数功能一览

引用https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

1. JNI Native String 函数

​ JNI支持两种编码 Unicode (16-bit characters) and UTF-8 (encoded in 1-3 bytes) 形式的string,其中UTF-8形式的类似以\0结尾的c风格字符串

​ 1. 函数有

// UTF-8 String (encoded to 1-3 byte, backward compatible with 7-bit ASCII)
// Can be mapped to null-terminated char-array C-string
const char * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);
   // Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding.
void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf);
   // Informs the VM that the native code no longer needs access to utf.
jstring NewStringUTF(JNIEnv *env, const char *bytes);
   // Constructs a new java.lang.String object from an array of characters in modified UTF-8 encoding.
jsize GetStringUTFLength(JNIEnv *env, jstring string);
   // Returns the length in bytes of the modified UTF-8 representation of a string.
void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize length, char *buf);
   // Translates len number of Unicode characters beginning at offset start into modified UTF-8 encoding 
   // and place the result in the given buffer buf.
  
// Unicode Strings (16-bit character)
const jchar * GetStringChars(JNIEnv *env, jstring string, jboolean *isCopy);
   // Returns a pointer to the array of Unicode characters
void ReleaseStringChars(JNIEnv *env, jstring string, const jchar *chars);
   // Informs the VM that the native code no longer needs access to chars.
jstring NewString(JNIEnv *env, const jchar *unicodeChars, jsize length);
   // Constructs a new java.lang.String object from an array of Unicode characters.
jsize GetStringLength(JNIEnv *env, jstring string);
   // Returns the length (the count of Unicode characters) of a Java string.
void GetStringRegion(JNIEnv *env, jstring str, jsize start, jsize length, jchar *buf);
   // Copies len number of Unicode characters beginning at offset start to the given buffer buf
  1. 说明

    1. 对于最常用的const char * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);

      1. 当分配失败 GetStringUTFChars返回NULL,所以一般调用后进行NULL值判断

      2. 第三个参数,代表是否拷贝,如果是JNI_TRUE,代表拷贝一份string的内容给返回值的指针

        ​ 如果是JNI_FALSE,代表返回直接指向string的指针,这种情况下native侧不应该修改指针的值

        ​ JNI尽可能返回一个直接指向string的指针,并且我们大多数都传递NULL

    2. 关于 ReleaseStringUTFChars()

      当你不需要返回GetStringUTFChars返回的指针释放内存和引用时,使用ReleaseStringUTFChars函数进行垃圾回收

    3. NewStringUTF()

      从C风格的字符串创建jstring字符串

posted @ 2021-01-10 23:54  make_wheels  阅读(164)  评论(0编辑  收藏  举报