Android NDK 开发教程四:TwoLibs示例
2012-05-13 08:52
204 查看
随Android NDK 提供的另外一个例子TwoLibs,其中有两个库,一个为动态库,一个为静态库,最终供Android Application使用的动态库使用静态库中的函数,如下图所示:
其中在first.c 中定义了一个简单的C函数
second.c 调用这个函数
为了介绍动态库调用静态库的方法,这个例子将两个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应用只可以调用动态库)
下面就可以使用ndk-build ,编译C代码,然后再使用Eclipse编译Java代码,运行结果如下:
其中在first.c 中定义了一个简单的C函数
int first(int x, int y) { return x+y; }
second.c 调用这个函数
jint Java_com_example_twolibs_TwoLibs_add( JNIEnv* env, jobject this, jint x, jint y ) { return first(x, y); }
为了介绍动态库调用静态库的方法,这个例子将两个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应用只可以调用动态库)
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代码,运行结果如下:
相关文章推荐
- Android NDK 开发教程五:TwoLibs示例
- Android NDK 开发教程三:Hello JNI 示例
- Android NDK 开发教程四:Hello JNI 示例
- Android简明开发教程二十四:总结及示例代码下载
- HTML5+开发移动app教程3-mui开发示例
- Kurento应用开发指南(以Kurento 5.0为模板) 之四:示例教程 一对一视频呼叫
- Android NDK 开发教程八:Box2D 的Android NDK实现
- HTML5+开发移动app教程3-mui开发示例
- C#开发Unity游戏教程循环遍历做出判断及Unity游戏示例
- Android简明开发教程十二:引路蜂二维图形库简介及颜色示例
- Android简明开发教程二十四:总结及示例代码下载
- (示例3)涂涂乐开发教程
- iOS APP开发集成Apple Pay与银联SDK开发教程(附示例代码)
- Android NDK 开发教程一:安装NDK
- android开发教程之view组件添加边框示例
- Android NDK 开发教程七:Application.mk
- Yii Framework 开发教程(27) 数据库-关联Active Record示例
- Android简明开发教程十三:Option Menu 画笔示例
- Android简明开发教程二十四:总结及示例代码下载
- android开发教程之wifi开发示例