Android Java passes string type data to C

Source: Internet
Author: User

This article then implements the "Android Java pass int type data to C" method is still not implemented:

Public native string Sayhelloinc (string s);

First put a tool method, the specific meaning of the following article will be introduced

/** * Convert a jstring to a C language char* type.*/Char* _JSTRING2CSTR (jnienv*env, jstring jstr) {    Char* Rtn =NULL; Jclass clsstring= (*env)->findclass (env,"java/lang/string"); Jstring Strencode= (*env)->newstringutf (env,"GB2312"); 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);//" the"memcpy (RTN, BA, Alen); Rtn[alen]=0; }    (*ENV)->releasebytearrayelements (env, Barr, BA,0); returnRtn;}

Then complete the Sayhelloinc function

/** Class:com_wuyudong_javapassdata_jni * method:sayhelloinc * Signature: (ljava/lang/string;) Ljava/lang/strin G */
jniexport jstring jnicall java_com_wuyudong_javapassdata_jni_sayhelloinc (jnienv*env, Jobject clazz, jstring jstr) { //invoking a tool method converts a string type in Java into a charx in the C language Char* CStr =_jstring2cstr (env, JSTR); intLen =strlen (CStr); inti; for(i =0; i < Len; i++) { * (CStr + i) + =1; } return(*env)Newstringutf (env, CStr);}

Add the following code to the Mainactivity.java:

     Public void passstring (View v) {        toast.maketext (Getapplicationcontext (), Jni.sayhelloinc ("Hello Yudong"), 0). Show ();    }

Done, run the project.

Android Java passes string type data to C

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.