鍍金池/ 教程/ Android/ TwoLibs 示例
安裝 NDK
application.mk
調(diào)試
Android.mk 文件
Hello JNI 示例
概述
Box2D 的 Android NDK 實(shí)現(xiàn)
TwoLibs 示例

TwoLibs 示例

隨 Android NDK 提供的另外一個(gè)例子 TwoLibs,其中有兩個(gè)庫(kù),一個(gè)為動(dòng)態(tài)庫(kù),一個(gè)為靜態(tài)庫(kù),最終供 Android Application 使用的動(dòng)態(tài)庫(kù)使用靜態(tài)庫(kù)中的函數(shù),如下圖所示:

http://wiki.jikexueyuan.com/project/android-ndk-development-tutorial/images/4.1.jpg" alt="picture4.1" />

其中在 first.c 中定義了一個(gè)簡(jiǎn)單的 C 函數(shù)


    int first(int x, int y)
    {
     return x+y;
    }

second.c 調(diào)用這個(gè)函數(shù)


    jint
    Java_com_example_twolibs_TwoLibs_add( JNIEnv*  env,
     jobject  this,
     jint x,
     jint y )
    {
     return first(x, y);
    }

為了介紹動(dòng)態(tài)庫(kù)調(diào)用靜態(tài)庫(kù)的方法,這個(gè)例子將兩個(gè) C 文件編譯成兩個(gè)模塊,這是通過(guò) android.mk 來(lái)定義的


    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)

註:當(dāng)然對(duì)於這個(gè)簡(jiǎn)單的例子,大可不必編譯成兩個(gè)模塊。

在 Android 應(yīng)用中調(diào)用動(dòng)態(tài)庫(kù)(Android 應(yīng)用只可以調(diào)用動(dòng)態(tài)庫(kù))


    public class TwoLibs extends Activity
    {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState)
     {
     super.onCreate(savedInstanceState);

     TextView  tv = new TextView(this);
     int   x  = 1000;
     int   y  = 42;

     // here, we dynamically load the library at runtime
     // before calling the native method.
     //
     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);
    }

下面就可以使用 ndk-build ,編譯 C 代碼,然後再使用 Eclipse 編譯 Java 代碼,運(yùn)行結(jié)果如下:

http://wiki.jikexueyuan.com/project/android-ndk-development-tutorial/images/4.2.jpg" alt="picture4.2" />

下一篇:安裝 NDK