반응형

들어가며

Android NDK란?

  • C/C++로 작성된 프로그램을 Android에서 실행할 수 있도록 해주는 개발 도구

예제

Calculator.h

  • 경로 : ~/app/src/main/cpp/Calculator.h
class Calculator {
public:
    int add(int a, int b);
};

Calculator.cpp

  • 경로 : ~/app/src/main/cpp/Calculator.cpp
#include "Calculator.h"

int Calculator::add(int a, int b) {
    return a + b;
}

native-lib.cpp

  • 경로 : ~/app/src/main/cpp/native-lib.cpp
#include <jni.h>
#include <string>
#include "Calculator.h"

using namespace std;

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_NativeLib_getMessage( // com.example.NativeLib.getMessage()
        JNIEnv *env,
        jobject thisObject
) {
    string hello = "Hello World";
    return env->NewStringUTF(hello.c_str());
}

extern "C" JNIEXPORT jint JNICALL
Java_com_example_NativeLib_add( // com.example.NativeLib.add()
        JNIEnv *env,
        jobject thisObject,
        jint a,
        jint b
) {
    Calculator calculator = Calculator();
    return calculator.add(a, b);
}

CMakeLists.txt

  • 경로 : ~/app/src/main/cpp/CMakeLists.txt
cmake_minimum_required(VERSION 3.10.2)

add_library(
        # Sets the name of the library.
        native_lib

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        Calculator.h
        Calculator.cpp
        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.
        native_lib

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

build.gradle

android {
    ...
    defaultConfig {
        ...
        externalNativeBuild {
            cmake {
                cppFlags '-std=c++17'
            }
        }
    }
    ...
    externalNativeBuild {
        cmake {
            path file('src/main/cpp/CMakeLists.txt')
            version '3.10.2'
        }
    }
}

NativeLib

class NativeLib {
    companion object {
        init {
            System.loadLibrary("native_lib")
        }
    }

    external fun getMessage(): String

    external fun add(a: Int, b: Int): Int
}

MainActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView = findViewById<TextView>(R.id.textView)
        val nativeLib = NativeLib()

        textView.text = "${nativeLib.getMessage()} : ${nativeLib.add(2, 3)}"
    }
}

참고

반응형

'Development > Android' 카테고리의 다른 글

[Android] 애드몹(Admob) 연동하기  (0) 2024.03.18
[Android] 무선으로 빌드하기  (0) 2024.01.07
[Android] Jenkins로 APK 빌드하기  (0) 2021.02.22
[Android] Chromecast  (0) 2021.02.16
[Android] ExoPlayer  (0) 2021.02.10

+ Recent posts