Jni的一个异常

时间:2023-03-09 18:38:11
Jni的一个异常

  UnsatisfiedLinkError:No implementation found for java.lang.String com.skymaster.hs.test4.MainActivity.getstringFromJNI();

就是桌这个路径下的方法stringFromJNI();没有被实现,看看全部代码

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
tv.append(getStringFromJNI());
} /**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
public native String getStringFromJNI();
}

下面是cpp目录中native-lib.cpp的代码

#include <jni.h>
#include <string>
using namespace std;
extern "C" jstring
Java_com_skymaster_hs_test4_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
} jstring
Java_com_skymaster_hs_test4_MainActivity_getStringFromJNI(
JNIEnv *env,
jobject /* this */) {
string hello = " Hello Android";
return env->NewStringUTF(hello.c_str());
}

这里虽然是c++的源文件,但是两个函数都是c的函数,所以需要用extern "C"(大写的C)来告诉c++编译器需要按照c的的方式来编译与链接。问题出在
extern "C"的作用范围,如果不用大括号包括2个函数就会出问题。修改如下就好了

#include <jni.h>
#include <string>
using namespace std;
extern "C" { jstring
Java_com_skymaster_hs_test4_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
} jstring
Java_com_skymaster_hs_test4_MainActivity_getStringFromJNI(
JNIEnv *env,
jobject /* this */) {
string hello = " Hello Android";
return env->NewStringUTF(hello.c_str());
}
}