Step-by-step learning ANDROIDNDK Programming (Java passes data to c)

Source: Internet
Author: User

This is already the fourth chapter of "Step-by-step learning ANDROIDNDK Programming" , in which we will pass code to C code in Java.

First, we create a new Android project "Ndkdata",

The first step:

The same first declares the native method, as follows:

public native int Add (int a,int b);p ublic native string Hellosir (string name);p ublic native int[] Intmethod (int[] Intarray );
Can see I've declared here three methods to pass different data types to C code

Step Two:

Since all of our methods are declared in Mainactivity.java, we need to first compile the Mainactivity.java with Javac as a. class file and then use Javah to generate the corresponding. h header file.

Compile the Mainactivity.java with Javac as a. class file : This is the Android project that you can run to generate a corresponding. class file in the Bin/classes directory.

under command line enter the directory where bin/classes is located : Execute Javah com.example.ndkdata.MainActivity to generate the corresponding com_example_ in this directory Ndkdata_mainactivity.h header file, the contents are as follows:

/* do don't EDIT this file-it was machine generated */#include <jni.h>/* Header for CLA SS Com_example_ndkdata_mainactivity */#ifndef _included_com_example_ndkdata_mainactivity#define _Included_com_     Example_ndkdata_mainactivity#ifdef __cplusplusextern "C" {#endif */* * class:com_example_ndkdata_mainactivity * Method: Add * Signature: (II) I */jniexport jint jnicall java_com_example_ndkdata_mainactivity_add (jnienv *, Jobject, Jint, J int);/* * class:com_example_ndkdata_mainactivity * Method:hellosir * Signature: (ljava/lang/string;) ljava/lang/st Ring */jniexport jstring jnicall Java_com_example_ndkdata_mainactivity_hellosir (jnienv *, Jobject, jstring);/* * CLASS:C om_example_ndkdata_mainactivity * Method:intmethod * Signature: ([i) [i */jniexport Jintarray jnicall java_com_example_ Ndkdata_mainactivity_intmethod (JNIEnv *, Jobject, jintarray); #ifdef __cplusplus} #endif #endif 
Next we create the JNI directory in the Ndkdata project, and then theCopy the Com_example_ndkdata_mainactivity.h file to the directory, and then create our C code: HELLO.C

Add the method generated in Com_example_ndkdata_mainactivity.h to the hello.c file here, you need to add a parameter, because the default is to generate only the method's parameter type, no Parameter object, and introduce the corresponding header file, as follows:

#include <stdio.h> #include <jni.h> #include "com_example_ndkdata_mainactivity.h" Jniexport jint Jnicall Java_com_example_ndkdata_mainactivity_add  (jnienv * env, Jobject obj, Jint x, Jint y) {      }jniexport jstring jnical L Java_com_example_ndkdata_mainactivity_hellosir  (jnienv * env, jobject obj, jstring jstr) {      }jniexport Jintarray jnicall java_com_example_ndkdata_mainactivity_intmethod  (jnienv * env, jobject obj, JintArray arr) {        }
The next step is to implement our C code, as follows:

#include <stdio.h> #include <jni.h> #include "com_example_ndkdata_mainactivity.h" Jniexport jint Jnicall java_com_example_ndkdata_mainactivity_add  (JNIENV * env, Jobject obj, Jint x, jint y) {    return x+y ;   }/** * return value char* This represents the first address of a char array  * &NBSP;JSTRING2CSTR converts the type of jstring in Java into a char string in the C language  */char*   JSTRING2CSTR (jnienv*   env,   jstring   jstr) {<span style= "White-space:pre" >& lt;/span> char*   RTN   =   Null;<span style= "White-space:pre" ></span> jclass   CLSSTR ing   =   (*env)->findclass (env, "java/lang/string"); String<span style= "White-space:pre" ></span> jstring   strencode   =   (*env) Newstringutf (env, "GB2312");  //get a Java string "GB2312" <span style= "White-space:pre" ></span> jmethodid   Mid   =   (* ENV)->getmethodid (env,clsstring,   "GetBytes",   "(ljava/lang/string;) [B");//[String.getbytes ("gb2312"), <span style= "White-space:pre" ></span> jbytearray   barr=   ( Jbytearray) (*env)->callobjectmethod (Env,jstr,mid,strencode); String. GetByte ("GB2312"); <span style= "White-space:pre" ></span> jsize   Alen   =   (*env)- >getarraylength (Env,barr); byte array length <span style= "White-space:pre" ></span> jbyte*   ba   =   (*env) Getbytearrayelements (env,barr,jni_false); <span style= "White-space:pre" ></span> if (Alen   >   0) <span style= "White-space:pre" ></span> {<span style= "White-space:pre" ></span>  rtn   =   (char*) malloc (alen+1);        //"<span" style= "White-space:pre" ></span>  memcpy (Rtn,ba,alen);< Span style= "White-space:pre" ></span>  rtn[alen]=0;<span style= "White-space:pre" ></span> }<span style= "White-space:pre" ></span> (*env)->releasebyteaRrayelements (env,barr,ba,0);  //<span style= "White-space:pre" ></span> return RTN;} Jniexport jstring jnicall java_com_example_ndkdata_mainactivity_hellosir  (JNIENV * env, jobject obj, jstring jstr) {   //In C language is no Java string<span style= "White-space:pre" ></span>char* CStr = Jstring2CStr (env, JSTR); <span style= "White-space:pre" ></span>//the string in the C language is the end <span style= "White-space:pre" "></span>char arr[7]= {" ', ' h ', ' e ', ' l ', ' l ', ' o ', ' white-space:pre '};<span style=, "></span> strcat (Cstr,arr); <span style= "White-space:pre" ></span>return (*env)->newstringutf (ENV,CSTR);     }jniexport jintarray jnicall java_com_example_ndkdata_mainactivity_intmethod  (JNIENV * env, Jobject obj, Jintarray arr) {    }

After writing the hello.c, you need to write android.mk, which reads as follows:

#交叉编译编译c/c++ code depends on the configuration file # Gets the path of the current android.mk  local_path: = $ (call My-dir) #变量初始化操作include $ (clear_vars) #libhello. In fact, the generated libhello.so is in front of our module name plus lib behind plus. Solocal_module    : = hellolocal_src_files: = Hello.cinclude $ (build_ Shared_library)
Now it is necessary to enter the Ndkdata root of the project under the command line of the Cygwine, execute the "ndk-build" command to generate the corresponding directly running binary files, note that each time after the "ndk-build" execution, it is best to clean the Android project.

After the "Ndk-build" succeeds, these library files need to be introduced in Java code:

static {        system.loadlibrary ("Hello");}

Note that the "Hello" here is the module name we wrote in the Android.mk file, which is the value of Local_module.

Now it's time to execute the native method of the declaration, which can be called directly in the Java code, isn't it simple?

SOURCE download








Step-by-step learning ANDROIDNDK Programming (Java passes 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.