10

JNI编程之字符串处理 - 故乡的樱花开了

 11 months ago
source link: https://www.cnblogs.com/luqman/p/string.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JNI编程之字符串处理

  java中的字符串类型是String,对应的jni类型是jstring,由于jstring是引用类型,所以我们不能像基本数据类型那样去使用它,我们需要使用JNIEnv中的函数去处理jstring,下面介绍一些常用的字符串处理函数。

  1.GetStringUTFChars()

  作用:将jstring类型转化为c中的const char *类型
  参数说明:
  string:jstring类型字符串
  isCopy:两种取值,JNI_TRUE/JNI_FALSE;JNI_TRUE表示返回的是c字符串是java类型字符串的拷贝,JNI_FALSE表示c字符串直接指向java字符串;实际开发中,我们不关心这个值是什么,直接传入nullptr即可

const char* GetStringUTFChars(jstring string, jboolean* isCopy)
{ return functions->GetStringUTFChars(this, string, isCopy); }

  2.ReleaseStringUTFChars()

  作用:用于释放通过GetStringUTFChars()函数获取的c字符串的内存,使用完这个c字符串之后一定要用这个函数释放内存,防止内存泄漏
  参数说明:
  string:jstring类型的字符串
  utf:对应的c字符串

void ReleaseStringUTFChars(jstring string, const char* utf)
{ functions->ReleaseStringUTFChars(this, string, utf); }

  3.NewStringUTF()

  作用:将c字符串转化为jstring类型

jstring NewStringUTF(const char* bytes)
{ return functions->NewStringUTF(this, bytes); }

  4.NewString()

  作用:将utf-16字符数组转化为jstring字符串
  参数说明:
  unicodeChars:字符数组
  len:字符数组的长度

jstring NewString(const jchar* unicodeChars, jsize len)
{ return functions->NewString(this, unicodeChars, len); }

  5.GetStringUTFLength()

  作用:获取jstring字符串的utf-8编码字符串长度

jsize GetStringUTFLength(jstring string)
{ return functions->GetStringUTFLength(this, string); }

  6.GetStringLength()

  作用:获取jstring字符串的utf-16编码字符串长度

jsize GetStringLength(jstring string)
{ return functions->GetStringLength(this, string); }

  7.GetStringChars()

  作用:将jstring类型的字符串转化为utf-16编码的字符数组

const jchar* GetStringChars(jstring string, jboolean* isCopy)
{ return functions->GetStringChars(this, string, isCopy); }

  8.ReleaseStringChars()

  释放由GetStringChars()函数获取的字符数组的内存

void ReleaseStringChars(jstring string, const jchar* chars)
{ functions->ReleaseStringChars(this, string, chars); }

  9.GetStringRegion()

  用于从Java字符串对象中获取指定范围的UTF-16编码的字符数据并存储在一个字符数组中

void GetStringRegion(jstring str, jsize start, jsize len, jchar* buf)
{ functions->GetStringRegion(this, str, start, len, buf); }

  10.GetStringUTFRegion()

  用于从Java字符串对象中获取指定范围的UTF-8编码的字符数据并存储在一个字符数组中

void GetStringUTFRegion(jstring str, jsize start, jsize len, char* buf)
{ return functions->GetStringUTFRegion(this, str, start, len, buf); }

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK