Android NDK 开发教程四:TwoLibs示例

jerry Android 2015年08月24日 收藏

隨Android NDK 提供的另外一個例子TwoLibs,其中有兩個庫,一個為動態庫,一個為靜態庫,最終供Android Application使用的動態庫使用靜態庫中的函數,如下圖所示:

其中在first.c 中定義了一個簡單的C函數

  1. int first(int x, int y)
  2. {
  3. return x+y;
  4. }

second.c 調用這個函數

  1. jint
  2. Java_com_example_twolibs_TwoLibs_add( JNIEnv*  env,
  3. jobject  this,
  4. jint     x,
  5. jint     y )
  6. {
  7. return first(x, y);
  8. }

為了介紹動態庫調用靜態庫的方法,這個例子將兩個C文件編譯成兩個模塊,這是通過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 應用中調用動態庫(Android應用只可以調用動態庫)

  1. public class TwoLibs extends Activity
  2. {
  3. /** Called when the activity is first created. */
  4. @Override
  5. public void onCreate(Bundle savedInstanceState)
  6. {
  7. super.onCreate(savedInstanceState);
  8.  
  9. TextView  tv = new TextView(this);
  10. int       x  = 1000;
  11. int       y  = 42;
  12.  
  13. // here, we dynamically load the library at runtime
  14. // before calling the native method.
  15. //
  16. System.loadLibrary("twolib-second");
  17.  
  18. int  z = add(x, y);
  19.  
  20. tv.setText( "The sum of " + x + " and " + y + " is " + z );
  21. setContentView(tv);
  22. }
  23.  
  24. public native int add(int  x, int  y);
  25. }

下面就可以使用ndk-build  ,編譯C代碼,然後再使用Eclipse編譯Java代碼,運行結果如下: