windows上搭建NDK开发环境:VS2013 + VisualGDB,参考链接:http://jingyan.baidu.com/article/a681b0de1a361c3b1843460c.html
VS2013新建一个安卓项目,选择创建一个安卓动态库,然后就可以开始编写C\C++代码了。
STL是C++开发最常用的一个库了,直接在程序中添加头文件:
#include <string> #include <vector> using std::string; using std::vector;</span>会报错,找不到对应的头文件,这是因为我们没有将STL头文件的路径告诉编辑器(NDK工程的配置和我们windows上开发的配置是不一样的)。
1、打开Application.mk,添加链接STL静态库:APP_STL := stlport_static
2、打开Android.mk,增加STL头文件和库文件完整路径:
LOCAL_C_INCLUDES := $(NDK_ROOT)/sources/cxx-stl/stlport/stlport LOCAL_STATIC_LIBRARIES := $(NDK_ROOT)/sources/cxx-stl/stlport/libs/armeabi/libstlport_static.a
NDK_ROOT是搭建开发环境时设置的环境变量,其路径就是NDK安装的位置根目录。
这时候,编译就不会有找不到头文件错误了。
static{ System.loadLibrary("AndroidProject2-shared"); System.loadLibrary("JniTest1-shared"); }
System.loadLibrary("JniTest1-shared")。
#ifdef __cplusplus extern "C" { #endif //函数声明处 #ifdef __cplusplus } #endif重新编译后,一切OK,安卓程序运行正常。
#include <jni.h> #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <unistd.h> #include <string> #include <vector> using std::string; using std::vector; #include "JniTest1.h" int MyTestFunction(int x) { return x * 2; } JNIEXPORT jint JNICALL Java_jni_Test_CalFileCount (JNIEnv *env, jobject obj, jstring str) { char szDir[128]; const char *p = env->GetStringUTFChars(str, NULL); if (NULL == p) return 0; strcpy(szDir, p); env->ReleaseStringUTFChars(str, p); printf("String from java : %s", szDir); vector<string> files; ListDir(szDir, files); return files.size(); } void ListDir(char* pPath, vector<string>& fileList) { DIR *pDir = opendir(pPath); if (NULL == pDir) return ; struct dirent *ent; char szPath[256], szFile[256]; while ((ent = readdir(pDir)) != NULL) { if ((strcmp(ent->d_name, ".") == 0) || (strcmp(ent->d_name, "..") == 0)) continue; sprintf(szPath, "%s/%s", pPath, ent->d_name); if (ent->d_type & DT_DIR) { //递归调用 ListDir(szPath, fileList); } else {//文件 fileList.push_back(szPath); } } closedir(pDir); }</span>
package jni; public class Test { static{ System.loadLibrary("AndroidProject2-shared"); System.loadLibrary("JniTest1-shared"); } public native int Add(int m, int b); public native int CalFileCount(String strDir); public int GetAdd(int m ,int b){ int sum = Add(m, b); System.out.println("调用C++函数,返回结果:" + sum); return sum; } public int GetCalFileCount(String strDir){ return CalFileCount(strDir); } }
int a = t1.GetAdd(100, 100); String str = "计算结果:" + a; System.out.println(str); Toast.makeText(activity, str, Toast.LENGTH_SHORT).show(); String str1 = "/system/lib/egl"; int b = t1.GetCalFileCount(str1); System.out.println("遍历文件个数:" + b);