Ndk learns 17:jni's Java call c&c++

Source: Internet
Author: User


A. Hello World 1. Defining function Prototypes
The function defined by the Native keyword is the JNI function

2. Generating the header file
Switch to src directory execution: (This process can be done automatically by scripting, such as automatically copying to the JNI directory) JAVAH-JNI package name. Class Name
Build under Root: Org_bing_testjni_mainactivity.h


3. Add JNI code to the projectProject Right-click Add native code-> input name->finish
More of the following article

Create a new application.mk, configure the relevant options (see the NDK's instructions for application in detail) App_abi:= x86 app_platform:= android-14 app_stl:= stlport_static app_cppflags +=-fexceptions app_cppflags +=-frtti

Also copy the. h file you just generated to the JNI directory

4. Implementing the native functionThe declaration of the function has been generated in the header file

the above functions are implemented in CPP: #include "org_bing_testjni_mainactivity.h" #include <stdio.h> #include <string> using namespace std; jstring jnicall java_org_bing_testjni_mainactivity_sayhello (jnienv* env, jobject obj, jstring name){ Const Char* pname = env-getstringutfchars(name , NULL); string str_info = "Hello world:";Str_info + = pname; jstring ret_str = env-newstringutf(str_info. C_str()); //C file Use (*env)->fun (env,xxx,...) The way to pass //(*ENV)->newstringutf (env, "Hello World"); return ret_str;}jniexport jint jnicall java_org_bing_testjni_mainactivity_add (jnienv *env, jobject obj, jint a, jint< /c17> b){ return a + b;}
Compiled in the Libs directory build libtestjni.so, package APK will automatically package the above functions into the APK
5. Using in Java loadLibraryStatic{    System. loadLibrary ("Testjni");}

You can then call directly: Log. D ("__bing__", SayHello ("BING"));Log. D ("__bing__", "5 + 3=" + Add (5,3));

Operating Effect:

























From for notes (Wiz)

Ndk learns 17:jni's Java call c&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.