zoukankan      html  css  js  c++  java
  • 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());
        }
    }
    这个只不过是自己的流水账,偶尔有一些心得,错误的地方概不负责
  • 相关阅读:
    博客园装修行动—我设计的新首页
    按作者名称查看评论
    [新功能]通过RSS阅读收藏夹
    [公告]首页小调整
    时间的格式化
    [公告]将读书心得区改成技术书评区
    [汇报]昨天晚上博客园的程序又出现了问题
    [公告]博客园已经成功迁移至新服务器
    [好消息]博客园乔迁新居
    [公告]博客园程序升级
  • 原文地址:https://www.cnblogs.com/ashitaka/p/5947026.html
Copyright © 2011-2022 走看看