栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android Jni Hello from c++

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android Jni Hello from c++

1.声明一个native方法 native方法不用实现

 //通过 native 关键字 声明了一个本地的方法 本地方法不用实现,需要用 JNI 调用 C 的代码来实现
 public native String stringFromJNI();

2.项目根目录下创建jni文件夹 在jni目录下创建 c 的代码
  C 函数命名规则 java_包名_native方法所在的类名_native方法名(JNIEnv* env, jobject this);

#include 
#include 

// java_包名_native函数所在类名_native方法名
//第二个参数 jobject 就是调用当前 native方法的 java 对象
//第一个参数 JNIEnv * JNIEnv 是结构体 JNINativeInterface 这个结构体的一级指针
//env 又是 JNIEnv 的一级指针 那么env 就是JNINativeInterface的二级指针
//结构体 JNINativeInterface 定义了大量了函数指针 这些函数指针在JNI 开发中十分常用
//(**env).func (*env)->
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_demo02_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject ) {
    std::string hello = "Hello from C++";
   // return env->NewStringUTF(hello.c_str());
    char * str = "hell word";
    //jstring  st = env->NewStringUTF(str);
    //通过 newStringUTF 方法把 c 的 字符串转换成 java 的String 类型
    jstring  st = (*env).NewStringUTF(str);
    return st;
}

3.cpp目录下CMakeLists.txt

cmake_minimum_required(VERSION 3.18.1)

project("demo02")

add_library( # Sets the name of the library.
        demo02

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        native-lib.cpp)

find_library( # Sets the name of the path variable.
        log-lib

        # Specifies the name of the NDK library that
        # you want CMake to locate.
        log)

target_link_libraries( # Specifies the target library.
        demo02

        # links the target library to the log library
        # included in the NDK.
        ${log-lib})

4.通过Android studio 开发工具,点击Build菜单下的 Rebuild Project, 编译.c/cpp 文件,生产so文件

5.调用.so 文件,需要使用System.loadLibrary来加载.so文件

 static {
        System.loadLibrary("demo02");
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/749120.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号