使用NDK往往都會include其他的library
從NDK的sample code也可以看到一個two-libs的範例
使用上也是很簡單
Java檔先把library載入並呼叫C function:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
int x = 1000;
int y = 42;
System.loadLibrary("twolib-second");
int z = add(x, y);
tv.setText( "The sum of " + x + " and " + y + " is " + z );
setContentView(tv);
}
public native int add(int x, int y);
撰寫兩個C 檔
//first.c
#include "first.h"
int first(int x, int y)
{
return x + y;
}
//second.c
#include "first.h"
#include <jni.h>
jint
Java_com_example_twolibs_TwoLibs_add( JNIEnv* env,
jobject this,
jint x,
jint y )
{
return first(x, y);
}
最後是JNI的Android.mk
LOCAL_PATH:= $(call my-dir)
# first lib, which will be built statically
#
include $(CLEAR_VARS)
LOCAL_MODULE := libtwolib-first
LOCAL_SRC_FILES := first.c
include $(BUILD_STATIC_LIBRARY)
# second lib, which will depend on and include the first one
#
include $(CLEAR_VARS)
LOCAL_MODULE := libtwolib-second
LOCAL_SRC_FILES := second.c
LOCAL_STATIC_LIBRARIES := libtwolib-first
include $(BUILD_SHARED_LIBRARY)
再參照Android-NDK-1篇進行編譯後, 就可以實現APP使用JNI載入其他native libary的功能囉!
運行畫面如下: