cygwin+ndk+eclipse之JNI调用C函数
1人收藏此文章, 我要收藏发表于4个月前(2012-07-12 15:55) , 已有
177次阅读 ,共
0个评论
1.新建android项目testJNI
2.在TestJNIActivity里添加:
01 | public class TestJNIActivity extends Activity { |
04 | System.loadLibrary( "hello" ); |
06 | private native String myCFunction(); |
07 | /** Called when the activity is first created. */ |
09 | public void onCreate(Bundle savedInstanceState) { |
10 | super .onCreate(savedInstanceState); |
11 | setContentView(R.layout.main); |
13 | String msg=myCFunction(); |
14 | Toast.makeText( this , msg, Toast.LENGTH_LONG).show(); } |
3.在项目里新建一个jni文件夹,里面新建2个文件,分别为Android.mk和hello.c内容分别如下:
Android.mk代码
1 | LOCAL_PATH := $(call my- dir ) |
5 | LOCAL_SRC_FILES := hello.c |
6 | include $(BUILD_SHARED_LIBRARY) |
hello.c代码
4 | jstring Java_com_jni_TestJNIActivity_myCFunction |
5 | (JNIEnv* env,jobject javaThis) { |
6 | return (*env)->NewStringUTF(env, "Hello from native C code!" ); |
4.打开cygwin终端,cd进入到当前项目中jni文件夹所在的目录,然后ls下,里面有上面2个文件。接着用命令
$NDK/ndk-build进行编译,出现如下信息则表示编译成功。
1 | Administrator@BK /cygdrive/e/android/testJNI/jni |
3 | Compile thumb : hello <= hello.c |
4 | SharedLibrary : libhello.so |
5 | Install : libhello.so => libs/armeabi/libhello.so |
之后再eclipse中按F5刷新,会出现2个文件夹,分别为libs和obj,里面都有libhello.so文件.libhello.so就是要TestJNIActivity中
2 | System.loadLibrary( "hello" ); |
调用的函数库,其中调用时只写hello,默认会调用到libhello.so。
5.右键项目运行,在android模拟器中安装运行apk会显示"Hello from native C code!"字样
OK,大功告成O(∩_∩)O