Android--jni Universal Tool method

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/47002207
1. Convert Java string to C + + string

/** * Tool Method * Convert Java String to C + + String * Returns the first address of an array of strings */char* Jstring2cppstr (jnienv* env, jstring jstr, jstring encode) {char* RTN = N Ull;jclass clsstring = Env->findclass ("java/lang/string"); jstring Strencode = Env->newstringutf (encode); Jmethodid mid = Env->getmethodid (clsstring, "GetBytes", "(ljava/lang/string;) [B"); Jbytearray Barr = (Jbytearray) Env->callobjectmethod (Jstr, Mid,strencode); String. GetByte ("GB2312"); 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;}
2. Convert Java string to C string

/** * Tool Method * Converts a Java string to a C string * Returns the first address of an array of strings */char* Jstring2cstr (jnienv* env, jstring jstr, jstring encode) {char* RTN = NULL; Jclass clsstring = (*env)->findclass (env, "java/lang/string"); jstring Strencode = (*env)->newstringutf (env, encode); Jmethodid mid = (*env)->getmethodid (env, clsstring, "GetBytes", "(ljava/lang/string;) [B"); Jbytearray Barr = (Jbytearray) (*env)->callobjectmethod (env, JSTR, Mid,strencode); String. GetByte ("GB2312"); Jsize alen = (*env)->getarraylength (env, Barr); jbyte* ba = (*env) Getbytearrayelements (env, Barr, Jni_false); if (Alen > 0) {rtn = (char*) malloc (alen + 1);//"memcpy" (RTN, BA, Alen); r Tn[alen] = 0;} (*env)->releasebytearrayelements (env, Barr, BA, 0); return RTN;}
Warm tip: You can get the complete JNI invocation sample code to the link http://download.csdn.net/detail/l1028386804/8922611

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android--jni Universal Tool method

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: info-contact@alibabacloud.com 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.