我正在使用 NDK 将 java 与 C++ 结合起来,这是我的代码:
MainActivity.java
public class MainActivity extends Activity {
/*Don't forget to load the library!!*/
static {
System.loadLibrary("NDK1");
}
public native String exec(String cmd);
安卓.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# Here we give our module name and source file(s)
LOCAL_MODULE := NDK1
LOCAL_SRC_FILES := NDK1.cpp
include $(BUILD_SHARED_LIBRARY)
应用程序.mk
APP_ABI := armeabi armeabi-v7a
APP_STL := gnustl_static
NDK1.cpp
#include <string>
#include <iostream>
#include <stdio.h>
#include <jni.h>
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
jstring Java_com_example_ndk1_MainActivity_exec(JNIEnv* env, jobject javaThis , jstring cmd) {
char * res;
res = env->GetStringUTFChars(cmd ) ;
std::string result = exec(res);
return env->NewStringUTF(result);
}
但是有这个错误!
$ /cygdrive/c/android-ndk-r4/ndk-build
make: Warning: File `/cygdrive/c/android-ndk-r4/build/core/import-locals.mk' has modification time 140680622 s in the future
Compile++ thumb : NDK1 <= NDK1.cpp
jni/NDK1.cpp: In function '_jstring* Java_com_example_ndk1_MainActivity_exec(JNIEnv*, jobject, jstring)':
jni/NDK1.cpp:22:39: error: no matching function for call to '_JNIEnv::GetStringUTFChars(_jstring*&)'
jni/NDK1.cpp:22:39: note: candidate is:
C:/android-ndk-r4/platforms/android-14/arch-arm/usr/include/jni.h:860:17: note: char const* _JNIEnv::GetStringUTFChars(jstring, jboolean*)
C:/android-ndk-r4/platforms/android-14/arch-arm/usr/include/jni.h:860:17: note: candidate expects 2 arguments, 1 provided
jni/NDK1.cpp:25:36: error: no matching function for call to '_JNIEnv::NewStringUTF(std::string&)'
jni/NDK1.cpp:25:36: note: candidate is:
C:/android-ndk-r4/platforms/android-14/arch-arm/usr/include/jni.h:854:13: note: _jstring* _JNIEnv::NewStringUTF(char const*)
C:/android-ndk-r4/platforms/android-14/arch-arm/usr/include/jni.h:854:13: note: no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'char const*'
/cygdrive/c/android-ndk-r4/build/core/build-binary.mk:269: recipe for target `obj/local/armeabi/objs/NDK1/NDK1.o' failed
make: *** [obj/local/armeabi/objs/NDK1/NDK1.o] Error 1