Skip to content

Instantly share code, notes, and snippets.

@jpzhu
Last active December 25, 2015 08:29
Show Gist options
  • Save jpzhu/6946818 to your computer and use it in GitHub Desktop.
Save jpzhu/6946818 to your computer and use it in GitHub Desktop.
JNI 使用摘记(1)

(1) 在需要访问jni函数的.java源文件里代码加上native样式的声明,例如

   public native void printhello();

(2) 调用javah命令,从.java生成的.class文件中生成jni需要的头文件。这样的头文件里的函数类型确保了.java能正确访问.c中的方法.

javah -o jni_hello.h -jni -classpath /home/jpzhu/anvil/out/target/common/obj/APPS/HelloWorld_intermediates/classes/ com.igdium.helloworld.HelloWorldAndroidActivity

生成的文件内容如下:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_igdium_helloworld_HelloWorldAndroidActivity */

#ifndef _Included_com_igdium_helloworld_HelloWorldAndroidActivity
#define _Included_com_igdium_helloworld_HelloWorldAndroidActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_igdium_helloworld_HelloWorldAndroidActivity
 * Method:    printhello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_igdium_helloworld_HelloWorldAndroidActivity_printhello
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

然后我们只需在jni_hello.c里实现这个Java_com_igdium_helloworld_HelloWorldAndroidActivity_printhello函数。

JNIEXPORT void JNICALL Java_com_igdium_helloworld_HelloWorldAndroidActivity_printhello
  (JNIEnv *env, jobject thiz)
{
        ALOGD("jni method is called()");
}

(3)要想在.java里能使用jni库代码,还得提前将该jni库加载。在.java的类文件里加如下代码.

static {
    System.loadLibrary("jni_hello");
}

(4) 因为应用要用到jni库,则需要在其软件包里加入该库。修改应用的Android.mk文件为

LOCAL_JNI_SHARED_LIBRARIES := libhelloworld

(5) jni编译时的模块名要和上面的库名要对的上,其内容如下

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

TARGET_PLATFORM := android-3
LOCAL_MODULE    := libjni_hello
LOCAL_PACKAGE_NAME = libjni_hello
LOCAL_SRC_FILES := jni_hello.c
LOCAL_MODULE_TAGS := optional

LOCAL_SHARED_LIBRARIES := liblog libcutils

include $(BUILD_SHARED_LIBRARY)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment