美文网首页
Android NDK(JNI)详解教程三 Java调用JNI方

Android NDK(JNI)详解教程三 Java调用JNI方

作者: Kael_Zhang的安卓笔记 | 来源:发表于2023-03-01 08:48 被阅读0次

JAVA调用

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring JNICALL
Java_com_sample_projectname_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}
public class MainActivity extends AppCompatActivity {

    // Used to load the 'myndk' library on application startup.
    static {
        System.loadLibrary("projectname");
    }

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Example of a call to a native method
        binding.tvjni.setText(stringFromJNI());
    }

    /**
     * A native method that is implemented by the 'myndk' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}

编译配置

android {
    defaultConfig {
        externalNativeBuild {
            cmake {
                // 支持 c++11,配置内容仅举例,具体以实际项目需求为准
                cppFlags '-std=c++11'
                // 需要运行的 CPU 类型,配置内容仅举例,具体以实际项目需求为准
                abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
            }
        }
    }
    
    // cmake 配置,以下是默认配置,配置内容仅举例,具体以实际项目需求为准 
    externalNativeBuild {
        cmake {
            path file('src/main/cpp/CMakeLists.txt')
            version '3.18.1'
        }
    }
}

相关文章

网友评论

      本文标题:Android NDK(JNI)详解教程三 Java调用JNI方

      本文链接:https://www.haomeiwen.com/subject/zujlldtx.html