10:java simple data transfer between Android technology and C language

Source: Internet
Author: User

Because of the many types of inconsistencies between the C and Java languages, data type conversions are required when using native. The following illustrates passing data by passing integers, strings, integer arrays, and Java static methods, respectively.

1. Create a native method

We create a separate Nativeclass class to hold the native method

1  Packagecom.forsta.ndk;2 3  Public classNativeclass {4      Public native intAddintXinty);5      Public nativestring showstring (String str);6      Public native int[] Array (int[] a);7      Public Static native intSubintXinty);8}

2. Get the corresponding header file

By using the Javah com.forsta.ndk.Native in the appropriate directory, get the Com_forsta_ndk_nativeclass.h

1 /*Do not EDIT this file-it are machine generated*/2#include <jni.h>3 /*Header for Class Com_forsta_ndk_nativeclass*/4 5 #ifndef _included_com_forsta_ndk_nativeclass6 #define_included_com_forsta_ndk_nativeclass7 #ifdef __cplusplus8 extern "C" {9 #endifTen /* One * Class:com_forsta_ndk_nativeclass A * Method:add - * Signature: (II) I -  */ the jniexport jint jnicall java_com_forsta_ndk_nativeclass_add -(JNIENV *, Jobject, Jint, jint); -  - /* + * Class:com_forsta_ndk_nativeclass - * method:showstring + * Signature: (ljava/lang/string;) ljava/lang/string; A  */ at jniexport jstring jnicall java_com_forsta_ndk_nativeclass_showstring -(JNIENV *, Jobject, jstring); -  - /* - * Class:com_forsta_ndk_nativeclass - * Method:array in * Signature: ([i) [I -  */ to jniexport jintarray jnicall java_com_forsta_ndk_nativeclass_array +(JNIENV *, Jobject, Jintarray); -  the /* * * Class:com_forsta_ndk_nativeclass $ * Method:subPanax Notoginseng * Signature: (II) I -  */ the jniexport jint jnicall java_com_forsta_ndk_nativeclass_sub +(JNIENV *, Jclass, Jint, jint); A  the #ifdef __cplusplus + } - #endif $ #endif

3. Implement the method in the header file

1#include <stdio.h>2#include <jni.h>3#include <malloc.h>4#include"Com_forsta_ndk_nativeclass.h"5 6 7 /**8 * Return value char* This represents the first address of a char array9 * JSTRING2CSTR Converts the type of jstring in Java into a char string in the C languageTen  */ One Char* JSTRING2CSTR (jnienv*env, jstring jstr) A { -      Char* Rtn =NULL; -Jclass clsstring = (*env)->findclass (env,"java/lang/string");//String theJstring Strencode = (*env)->newstringutf (env,"GB2312");//get a Java string "GB2312" -Jmethodid mid = (*env)->getmethodid (env,clsstring,"getBytes","(ljava/lang/string;) [B");//[String.getbytes ("gb2312"); -Jbytearray barr= (Jbytearray) (*env)->callobjectmethod (Env,jstr,mid,strencode);//String. GetByte ("GB2312"); -Jsize alen = (*env)->getarraylength (Env,barr);//the length of a byte array +jbyte* ba = (*env)getbytearrayelements (env,barr,jni_false); -      if(Alen >0) +      { ARTN = (Char*) malloc (alen+1);//" the" at memcpy (Rtn,ba,alen); -rtn[alen]=0; -      } -(*env)->releasebytearrayelements (Env,barr,ba,0);// -      returnRtn; - } in  - jniexport jint jnicall java_com_forsta_ndk_nativeclass_add to(JNIENV *env, Jobject obj, Jint x, Jint y) { +     returnx+y; - } the  * jniexport jstring jnicall java_com_forsta_ndk_nativeclass_showstring $(JNIENV *env, Jobject obj, jstring str) {Panax Notoginseng     //no string type in C language -     Char* s=jstring2cstr (ENV,STR); the     //the strings in the C language End with '/0 ' +     Chars1[7]={' ','h','e','L','L','o',' /'}; A strcat (S,S1); the     return(*env)Newstringutf (env,s); + } -  $ jniexport jintarray jnicall java_com_forsta_ndk_nativeclass_array $(JNIENV *env, Jobject obj, Jintarray arr) { -     //1. Get array length -     //2. Modify each data the     intSize= (*env)getarraylength (Env,arr); -     int* array= (*env)->getintarrayelements (Env,arr,0);Wuyi     intI=0; the      for(; i<size;i++){ -array[i]+=Ten; Wu     } -     returnarr; About  $ } - jniexport jint jnicall java_com_forsta_ndk_nativeclass_sub -(JNIENV *env, Jclass Clazz, Jint x, Jint y) { -     returnX-y; A}

Add a click event in 4.MainActivity

1 @Override2      Public voidOnClick (View v) {3         intID =V.getid ();4         Switch(ID) {5          CaseR.ID.BT1:6             intResult=nativeclass.add (10, 90);7Toast.maketext (Getapplicationcontext (), "Show results:" +result, Toast.length_short). Show ();8              Break;9          CaseR.ID.BT2:TenToast.maketext (Getapplicationcontext (), nativeclass.showstring ("Forsta"), Toast.length_short). Show (); One              Break; A          CaseR.ID.BT3: -             int[] arr={1,2,3,4,5}; - Nativeclass.array (arr); theString s = ""; -              for(intI:arr) { -s+=i+ ""; -             } + Toast.maketext (Getapplicationcontext (), S,toast.length_short). Show (); -              Break; +          CaseR.ID.BT4: A             intResult1=nativeclass.sub (90, 10); atToast.maketext (Getapplicationcontext (), "Subtraction display result:" +result1, Toast.length_short). Show (); -              Break; -         default: -              Break; -         } -          in}

5. Demo

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.