前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何向已有的项目中添加C/C++代码?

如何向已有的项目中添加C/C++代码?

作者头像
故乡的樱花开了
发布2023-10-22 13:59:40
1850
发布2023-10-22 13:59:40
举报
文章被收录于专栏:Android技术专栏Android技术专栏

第一步:

  我们需要在src/main下面建立一个cpp目录,然后在其中写一个CMakeLists.txt文件和一个cpp文件,直接给出代码:

代码语言:javascript
复制
#CMakeLists.txt文件
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.18.1)

# Declares and names the project.

project("hellondk")

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
        hellondk

        # Sets the library as a shared library.
        SHARED

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

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

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)

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
        hellondk

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

  native-lib.cpp文件的代码如下:

代码语言:javascript
复制
#include <jni.h>
#include <string>

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

  然后在app/build.gradle文件中添加以下代码:

代码语言:javascript
复制
android {
    namespace 'com.example.myapplication'
    compileSdk 32

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }//新增代码
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"    //指定CMakeLists.txt文件的路径
        }
    }//新增代码
}

  接下来就可以调用c++代码了:

代码语言:javascript
复制
public class MainActivity extends AppCompatActivity {
    private TextView tv_display;
    static{
        System.loadLibrary("hellondk");
    }
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_display = findViewById(R.id.tv_display);
        tv_display.setText(stringFromJNI());
    }
    public native String stringFromJNI();
}

  需要注意的是:本地函数声明public native String stringFromJNI()一定要在Java_com_example_myapplication_MainActivity_stringFromJNI函数名指定的包和类下,要不然程序会出错。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-07-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档