Android 簡單的JNI編程

來源:互聯網
上載者:User

標籤:android   style   blog   color   java   ar   strong   for   檔案   

1、先是編寫包含 native 方法的類庫

package com.miles.libs;public class Hello {        // 載入本地庫    static {        System.loadLibrary("Hello");    }    // 本地庫中的方法    public native String hello();}

 

2、用javah產生 c/c++ 標頭檔

javah -classpath 編譯目錄 類名

javah -classpath ./bin/classes com.miles.libs.Hello

產生的標頭檔:com_miles_libs_Hello.h

/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class com_miles_libs_Hello */#ifndef _Included_com_miles_libs_Hello#define _Included_com_miles_libs_Hello#ifdef __cplusplusextern "C" {#endif/* * Class:     com_miles_libs_Hello * Method:    hello * Signature: ()Ljava/lang/String; */JNIEXPORT jstring JNICALL Java_com_miles_libs_Hello_hello  (JNIEnv *, jobject);#ifdef __cplusplus}#endif#endif

PS:此檔案在你調用javah命令的目錄裡面

 

3、建立jni檔案目錄 將標頭檔拷貝進去,在目錄時面編寫c/c++檔案

代碼檔案:com_miles_libs_Hello.c

#include <jni.h>#include "com_miles_libs_HelloLibs.h"JNIEXPORT jstring JNICALL Java_com_miles_libs_Hello_hello(JNIEnv *env, jobject thiz);{    return (*env)->NewStringUTF(env, "Hello JNI !");}

 

4、編寫 Android.mk檔案

LOCAL_PATH      := $(call my-dir)include         $(CLEAR_VARS)LOCAL_MODULE    := HelloLOCAL_SRC_FILES := com_miles_libs_Hello.cinclude         $(BUILD_SHARED_LIBRARY)

關於mk檔案的編寫請自行查閱

 

5、編譯在配置好 ndk 的環境下進行編譯

我這裡用的是  android-ndk-r8c  這個版本編譯的,在過高的版本編譯會報錯,沒有深入研究!

 

Android 簡單的JNI編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.