Java code calls C code JNI

Source: Internet
Author: User

1 The interface for defining a C method is equivalent to the implementation of an interface interface defined in Java code that is implemented by the C language

public native int login (String password);

2 Implementing C code

In the directory of the Android project under SRC, you can use the command: (javah-jni full-class name) to generate a corresponding C-language function header file

#include <stdio.h>
#include "Com_qushaohui_aliwangwang_mainactivity.h"

int login (char* psw) {

char* rightpwd = "123";
if (strcmp (psw,rightpwd)) {
return 302;
}else{
return 200;
}
}

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); //
return RTN;
}

Jniexport Jint Jnicall Java_com_qushaohui_aliwangwang_mainactivity_login
(JNIENV * env, jobject obj, jstring str)
{
char* C = jstring2cstr (ENV,STR);
return login (c);
}

3 tell the compiler how to package C code into a function library to generate a android.mk file

Local_path: = $ (call My-dir)

Include $ (clear_vars)
# corresponding to the name of the function library
Local_module: = Hello
# files corresponding to C code
Local_src_files: = hello.c

Include $ (build_shared_library)

4 Packaging C code into a function library used in the installation environment

Execute Command ndk-build

5-Step introduction of library functions in Java code

6 How to use

Java code calls C code JNI

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.