안녕하세요. 메로나입니다.
오늘은 Android와 Flutter를 공부하면서 NDK가 종종 나오는데 왜 쓰이는지 공부하겠습니다.
NDK란?
- C와 C++ 언어를 사용하여 Android 애플리케이션의 일부를 구현할 수 있도록 지원하는 도구 모음
- 개발자는 성능이 중요한 컴퓨팅 작업을 최적화하거나, 기존의 C/C++ 라이브러리를 재사용할 수 있습니다.
NDK의 주요 구성 요소
- 해더 파일: Android API에 대한 헤더 파일을 제공합니다.
- 빌드 도구: ndk-build와 Gradle을 사용하여 네이트브 라이브러리를 컴파일합니다.
- 디버깅 도구: LLDB와 디버거를 제공합니다.
- 샘플 코드: NDK 활용 예제를 제공합니다.
NDK를 사용하는 일반적인 흐름
- 프로젝트 생성: Android 스튜디오에서 새로운 프로젝트를 생성합니다.
- NDK 및 CKMake 설치: SDK Manager에서 NDK와 CMake를 설치합니다.
- 네이티브 코드 작성: src/main/cpp 디렉터리에 C/C++ 소스 파일을 추가합니다.
- CMake 빌드 스크립트 작성: CMakeLists.txt 파일을 생성하여 네이티브 라이브러리의 빌드 방법을 정의합니다.
- Gradle 설정: build.gradle 파일에서 CMake 빌드 스크립트를 참조하도록 설정합니다.
- 네이티브 코드 호출: 자바 코드에서 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());
}
}
'Android' 카테고리의 다른 글
| [Android] ImageView의 scaleType 속성 (0) | 2025.05.08 |
|---|---|
| [Android] Context (0) | 2025.04.06 |
| [Android] AOSP(Android Open Source Project) (0) | 2025.03.07 |
| [Android] 안드로이드 리다이렉션 처리 (0) | 2025.02.28 |
| [Android] 미디어 프로젝션(Media Projection) (0) | 2025.02.27 |