Conversion between JNI jstring and char *

Source: Internet
Author: User
========================================================== =============================== Original blog, reprinted please declare the source of Electronic coffee (original id blue rock) ========================================================== ================================

Conversion between JNI jstring and char *

/+++++++++++++++++++++++++//jstring to char*//NOTICE: you need free return value,like free(ch)char* jstringToChar(JNIEnv* env, jstring jstr){char* rtn = NULL;jclass clsstring = env->FindClass("java/lang/String");jstring strencode = env->NewStringUTF("utf-8");jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");jbyteArray barr= (jbyteArray)env->CallObjectMethod(jstr, mid, strencode);env->DeleteLocalRef( strencode);jsize alen = env->GetArrayLength(barr);jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);if (alen > 0){rtn = (char*)malloc(alen + 1);memcpy(rtn, ba, alen);rtn[alen] = 0;}env->ReleaseByteArrayElements(barr, ba, 0);return rtn;}//char* to jstring//NOTICE: you need free return value,like  (*env)->DeleteLocalRef( env, myObj );jstring charToJstring(JNIEnv* env, const char* pat){jclass strClass = env->FindClass("Ljava/lang/String;");jmethodID ctorID = env->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");jbyteArray bytes = env->NewByteArray(strlen(pat));env->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*)pat);jstring encoding = env->NewStringUTF("utf-8");jstring result= (jstring) env->NewObject(strClass, ctorID, bytes, encoding);(env)->DeleteLocalRef(bytes);env->DeleteLocalRef( encoding);return result;}//+++++++++++++++++++++++++

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.