본문 바로가기

Android

[Android] NDK(Native Development Kit)

안녕하세요. 메로나입니다.

 

오늘은 Android와 Flutter를 공부하면서 NDK가 종종 나오는데 왜 쓰이는지 공부하겠습니다.

 

NDK란?
  • C와 C++ 언어를 사용하여 Android 애플리케이션의 일부를 구현할 수 있도록 지원하는 도구 모음
  • 개발자는 성능이 중요한 컴퓨팅 작업을 최적화하거나, 기존의 C/C++ 라이브러리를 재사용할 수 있습니다.
NDK의 주요 구성 요소
  • 해더 파일: Android API에 대한 헤더 파일을 제공합니다.
  • 빌드 도구: ndk-build와 Gradle을 사용하여 네이트브 라이브러리를 컴파일합니다.
  • 디버깅 도구: LLDB와 디버거를 제공합니다.
  • 샘플 코드: NDK 활용 예제를 제공합니다.
NDK를 사용하는 일반적인 흐름
  1. 프로젝트 생성: Android 스튜디오에서 새로운 프로젝트를 생성합니다.
  2. NDK 및 CKMake 설치: SDK Manager에서 NDK와 CMake를 설치합니다.
  3. 네이티브 코드 작성: src/main/cpp 디렉터리에 C/C++ 소스 파일을 추가합니다.
  4. CMake 빌드 스크립트 작성: CMakeLists.txt 파일을 생성하여 네이티브 라이브러리의 빌드 방법을 정의합니다.
  5. Gradle 설정: build.gradle 파일에서 CMake 빌드 스크립트를 참조하도록 설정합니다.
  6. 네이티브 코드 호출: 자바 코드에서 JNI를 통해 네이티브 코드를 호출합니다.
NDK 예제
#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());
}

 

cmake_minimum_required(VERSION 3.4.1)

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).
        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})

 

public class MainActivity extends AppCompatActivity {

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

    private native String stringFromJNI();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }
}