관리 메뉴

드럼치는 프로그래머

[JNI/NDK] Android NDK Overview ( 안드로이드 NDK 개요 ) 본문

★─Programing/☆─JNI | NDK

[JNI/NDK] Android NDK Overview ( 안드로이드 NDK 개요 )

드럼치는한동이 2016. 5. 31. 21:53

출처 : http://decsers.tistory.com/27

 

Android NDK Overview

Introduction:
소개:

The Android NDK is a set of tools that allows Android application developers
to embed native machine code compiled from C and/or C++ source files into
their application packages.
Android NDK 는 안드로이드 어플 개발자들이 C 혹은 C++ 소스를 어플의 패키지로 컴파일하여 포함한 네이티브 코드 라이브러리를 사용할 수 있게 해주는 도구들의 모음입니다. 

IMPORTANT:
  The Android NDK can only be used to target Android system images
  running Cupcake (a.k.a 1.5) or later versions of the platform.
중요함:
  Android NDK 는 목표로하는 타겟 안드로이드 시스템의 이미지(예를 들면 컵케이크, 1.5 같은) 혹은 이후의 버젼에서만 사용될 수 있습니다.

  1.0 and 1.1 system images are specifically *not* supported due to
  subtle ABI and toolchain changes that happened for the 1.5 release.
1.0과 1.1 시스템 이미지는 ABI 와 툴체인이 변경되어 지원되지 않습니다.


I. Android NDK Goals: 안드로이드 NDK의 목표
---------------------

The Android VM allows your application's source code to call methods
implemented in native code through the JNI. In a nutshell, this means that:
안드로이드 버츄얼 머신은 JNI를 통해서 네이티브 코드를 호출할 수 있게 해줍니다. 즉

  - Your application's source code will declare one or more methods
    with the 'native' keyword to indicate that they are implemented through
    native code. E.g.:
 - 여러분의 어플 소스코드는 네이티브 코드를 통해서 구현된 소스를 가리키는 'native'라는 키워드를 가진 메소르들 하나 이상 선언할 것입니다.

      native byte[]  loadFile(String  filePath); 

  - You must provide a native shared library that contains the
    implementation of these methods, which will be packaged into your
    application's .apk. This library must be named according to standard
    Unix conventions as lib<something>.so, and shall contain a standard JNI
    entry point (more on this later). For example:
  - 여러분은 이러한 메소들의 구현을 포함한 공용 라이브러리를 제공해야만 합니다. 그리고 그 라이브러니는 여러분의 어플 패키지(.apk)에 포함될 것입니다. 이 라이브러리는 표준 유닉스의 전통에 맞는 lib<something>.so라는 명명 규칙을 따라야만 합니다. 그리고, 표준 JNI 엔트리 포인트를 포함해야만 합니다. 예를들면

      libFileLoader.so

  - Your application must explicitely load the library. For example, to load
    it at application startup, simply add the following to its source code:
  - 여러분의 어플은 명시적으로 그 라이브러리를 로드해야만 합니다. 예를들면, 어플 시작할 때 로드하기 위해서는,
   단지 아래와 같은 소스를 포함해 주십시오.

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

    Note that you should not use the 'lib' prefix and '.so' suffix here.
    여러분은 'lib'라는 접두사와 '.so'라는 접미어는 쓰지 않는것을 명심해야 합니다.


The Android NDK is a complement to the Android SDK that helps you to:
안드로이드 NDK는 SDK의 보조적인 역활을 하면서 여러분을 도와줍니다.

  - Generate JNI-compatible shared libraries that can run on the Android
    1.5 platform (and later) running on ARM CPUs.
  - ARM CPU에서 동작하는 1.5 혹은 그 이후 플랫폼에서 동작하는 JNI 호환 공유 라이브러리를 만듭니다.

  - Copy the generated shared libraries to a proper location of your
    application project path, so they will be automatically added to your
    final (and signed) .apks
  - 여러분의 어플 프로젝트의 적절한 위치에 그 라이브러리를 복사합니다. 자동으로 포함이 됩니다.

  - In later revisions of the NDK, we intend to provide tools that help
    debug your native code through a remote gdb connection and as much
    source/symbol information as possible.
  - 향후 버젼에서는, 리모트 gdb 연결를 통해서 디버그 할 수 있는 툴을 제공할 예정이며 소스와 심벌 정보를 가능하면 포함할 예정입니다.

Moreover, the Android NDK provides:
더우기, NDK는 

  - A set of cross-toolchains (compilers, linkers, etc..) that can
    generate native ARM binaries on Linux, OS X and Windows (with Cygwin)
  - 컴파일러, 링커등 여러개 툴체인들이 리눅스, 맥, 윈도우에서 ARM 바이너리 코드를 생성합니다.

  - A set of system headers corresponding to the list of stable native APIs
    supported by the Android platform. This corresponds to definitions that
    are guaranteed to be supported in all later releases of the platform.
  - 안정적인 네이티브 API의 리스트를 지원합니다. 

    They are documented in the file docs/STABLE-APIS.TXT
docs/STABLE-APIS.TXT 에 설명이 되어 있습니다.

    IMPORTANT:
    Keep in mind that most of the native system libraries in Android system
    images are not frozen and might changed drastically, or even deleted,
    in later updates and releases of the platform.
    중요함:
    안드로이드 시스템의 네이티브 시스템 라이브러리의 대부분은 안정적이지 않으며 언제라도 변경되거나 삭제될 수 있습니다. 


  - A build system that allow developers to only write very short build files
    to describe which sources need to be compiled, and how. The build system
    deals with all the hairy toolchain/platform/CPU/ABI specifics. Moreover,
    later updates of the NDK can add support for more toolchains, platforms,
    system interfaces without requiring changes in the developer's build
    files (more on this later).
  - 


II. Android NDK Non-Goals:
--------------------------

The NDK is *not* a good way to write generic native code that runs on Android
devices. In particular, your applications should still be written in the Java
programming language, handle Android system events appropriately to avoid the
"Application Not Responding" dialog or deal with the Android application
life-cycle.

Note however that is is possible to write a sophisticated application in
native code with a small "application wrapper" used to start/stop it
appropriately.

A good understanding of JNI is highly recommended, since many operations
in this environment require specific actions from the developers, that are
not necessarily common in typical native code. These include:

  - Not being able to directly access the content of VM objects through
    direct native pointers. E.g. you cannot safely get a pointer to a
    String object's 16-bit char array to iterate over it in a loop.

  - Requiring explicit reference management when the native code wants to
    keep handles to VM objects between JNI calls.


The NDK only provides system headers for a very limited set of native
APIs and libraries supported by the Android platform. While a typical
Android system image includes many native shared libraries, these should
be considered an implementation detail that might change drastically between
updates and releases of the platform.

If an Android system library is not explicitely supported by the NDK
headers, then applications should not depend on it being available, or
they risk breaking after the next over-the-air system update on various
devices.

Selected system libraries will gradually be added to the set of stable NDK
APIs.


III. NDK development in practice: 실전연습
---------------------------------

Here's a very rough overview of how you can develop native code with the
Android NDK:
NDK를 가지고 어떻게 네이티브 코드를 개발하는지에 대한 간단한 설명이있습니다.

  1/ Place your native sources under $PROJECT/jni/...
  1/ 네이티브 소스를 $PROJECT/jni/...에 위치시킵니다.

  2/ Write $PROJECT/jni/Android.mk to describe your sources
     to the NDK build system
  2/ NDK 빌드 시스템에 여러분 소스에 대한 설명을 $PROJECT/jni/Android.mk 에 작성합니다.

  3/ Optional: write $PROJECT/jni/Application.mk to describe your
     project in more details to the build system. You don't need
     one to get started though, but this allows you to target
     more than one CPU or override compiler/linker flags
     (see docs/APPLICATION-MK.TXT for all details).
  3/ 옵션 : 빌드 시스템에 프로젝트에 대한 설명을  $PROJECT/jni/Application.mk 에 작성하십시오. 하지만 꼭 필요하지는 않습니다. 그러나, 하나 이상의 CPU에 대한 타겟을 설정할 수 있으며 컴파일러와 링커의 설정을 덮어 쓸 수 있습니다. (see docs/APPLICATION-MK.TXT for all details 더욱 자세한 내용은  docs/APPLICATION-MK.TXT 잠조)

  4/ Build your native code by running "$NDK/ndk-build" from your
     project directory, or any of its sub-directories.
  4/ 프로젝트가 있는 디렉토리에서  "$NDK/ndk-build"를 실행하여 네이티브 코드를 만듭니다.

The last step will copy, in case of success, the stripped shared libraries
your application needs to your application's root project directory. You
will then need to generate your final .apk through the usual means.
마지막 단계는 , 성공했을때, 공유 라이브러리를 복사할 것입니다. 

Now, for a few more details: 자, 좀더 자세한 내용은 :


III.1/ Configuring the NDK: NDK 설정 
- - - - - - - - - - - - - -

Previous releases required that you run the 'build/host-setup.sh'
script to configure your NDK. This step has been removed completely
in release 4 (a.k.a. NDK r4).
NDK r4버전에서는 'build/host-setup.sh'를 실행할 필요가 없습니다.


III.2/ Placing C and C++ sources:
- - - - - - - - - - - - - - - - -

Place your native sources under the following directory:

    $PROJECT/jni/

Where $PROJECT corresponds to the path of your Android application
project.

You are pretty free to organize the content of 'jni' as you want,
the directory names and structure here will not influence the final
generated application packages, so you don't have to use pseudo-unique
names like com.<mycompany>.<myproject> as is the case for application
package names.

Note that C and C++ sources are supported. The default C++ file extensions
supported by the NDK is '.cpp', but other extensions can be handled as well
(see docs/ANDROID-MK.TXT for details).

It is possible to store your sources in a different location by adjusting
your Android.mk file (see below).


III.3/ Writing an Android.mk build script:
- - - - - - - - - - - - - - - - - - - - - -

An Android.mk file is a small build script that you write to describe your
sources to the NDK build system. Its syntax is described in details in
the file docs/ANDROID-MK.TXT.

In a nutshell, the NDK groups your sources into "modules", where each module
can be one of the following:

  - a static library
  - a shared library

You can define several modules in a single Android.mk, or you can write
several Android.mk files, each one defining a single module.

Note that a single Android.mk might be parsed several times by the build
system so don't assume that certain variables are not defined in them.
By default, the NDK will look for the following build script:

   $PROJECT/jni/Android.mk

If you want to define Android.mk files in sub-directories, you should
include them explicitely in your top-level Android.mk. There is even
a helper function to do that, i.e. use:

   include $(call all-subdir-makefiles)

This will include all Android.mk files in sub-directories of the current
build file's path.


III.4/ Writing an Application.mk build file (optional):
- - - - - - - - - - - - - - - - - - - - - - - - - - - -

While an Android.mk file describes your modules to the build system, the
Application.mk file describes your application itself. See the
docs/APPLICATION-MK.TXT document to understand what this file allows you
to do. This includes, among others:

   - The exact list of modules required by your application.

   - The CPU architecture(s) to generate machine code for.

  - Optional information, like whether you want a release or debug
    build, specific C or C++ compiler flags and others that should
    apply to all modules being built.

This file is optional: by default the NDK will provide one that simply
builds *all* the modules listed from your Android.mk (and all the makefiles
it includes) and target the default CPU ABI (armeabi).

There are two ways to use an Application.mk:

  - Place it under $PROJECT/jni/Application.mk, and it will be picked
    up automatically by the 'ndk-build' script (more on this later)

  - Place it under $NDK/apps/<name>/Application.mk, where $NDK
    points to your NDK installation path. After that, launch
    "make APP=<name>" from the NDK directory.

    This was the way this file was used before Android NDK r4.
    It is still supported for compatibility reasons, but we strongly
    encourage you to use the first method instead, since it is much
    simpler and doesn't need modifying / changing directories of the
    NDK installation tree.

Again, see docs/APPLICATION-MK.TXT for a complete description of its
content.


III.5/ Invoke the NDK build system:
- - - - - - - - - - - - - - - - - -

The preferred way to build machine code with the NDK is to use the
'ndk-build' script introduced with Android NDK r4. You can also use
a second, legacy, method that depends on creating a '$NDK/apps' subdirectory.

In both cases, a succesful build will copy the final stripped binary modules
(i.e. shared libraries) required by your application to your application's
project path (Note that unstripped versions are kept for debugging
purposes, there is no need to copy unstripped binaries to a device).


  1: Using the 'ndk-build' command:
  ---------------------------------

  The 'ndk-build' script, located at the top of the NDK installation path
  can be invoked directly from your application project directory (i.e. the
  one where your AndroidManifest.xml is located) or any of its sub-directories.
  For example:

    cd $PROJECT
    $NDK/ndk-build

  This will launch the NDK build scripts, which will automatically probe your
  development system and application project file to determine what to build.

  For example:

    ndk-build
    ndk-build  clean    --> clean generated binaries
    ndk-build  -B V=1   --> force complete rebuild, showing commands

  By default, it expects an optional file under $PROJECT/jni/Application.mk,
  and a required $PROJECT/jni/Android.mk.

  On success, this will copy the generated binary modules (i.e. shared
  libraries) to the appropriate location in your project tree. You can later
  rebuild the full Android application package either through the usual
  'ant' command, or the ADT Eclipse plugin.

  See docs/NDK-BUILD.TXT for a more complete description of what this script
  does and which options it can take.


  2: Using the $NDK/apps/<name>/Application.mk:
  ---------------------------------------------

  This build method was the only one before Android NDK r4 and is only
  supported for compatibility reason. We strongly recommend you to migrate
  to using the 'ndk-build' command as soon as possible, since we may remove
  legacy support in a later NDK release.

  It requires the following:

    1. Creating a sub-directory named $NDK/apps/<name>/ under
       your NDK installation directory (not your project path).

       Where <name> is an arbitrary name to decribe your application
       to the NDK build system (no spaces allowed).

    2. Write $NDK/apps/<name>/Application.mk, which then requires
       a definition for APP_PROJECT_PATH that points to your
       application project directory.

    3. Go to the NDK installation path on the command line then
       invoke the top-level GNUMakefile, as in:

         cd $NDK
         make APP=<name>

  The result will be equivalent to the first method, except for the fact
  that intermediate generated files will be placed under $NDK/out/apps/<name>/


IV. Rebuild your application package:
- - - - - - - - - - - - - - - - - - -

After generating the binaries with the NDK, you need to rebuild your
Android application package files (.apk) using the normal means, i.e.
either using the 'ant' command or the ADT Eclipse plugin.

See the Android SDK documentation for more details. The new .apk will
embed your shared libraries, and they will be extracted automatically
at installation time by the system when you install the package on a
target device.


V. Debugging support:
- - - - - - - - - - -

The NDK provides a helper script, named 'ndk-gdb' to very easily launch
a native debugging session of your applications.

Native debugging can *ONLY* be performed on production devices running
Android 2.2 or higher, and does not require root or privileged access, as
long as your application is debuggable.

For more information, read docs/NDK-GDB.TXT. In a nutshell, native debugging
follows this simple scheme:

   1. Ensure your application is debuggable (e.g. set android:debuggable
      to "true" in your AndroidManifest.xml)

   2. Build your application with 'ndk-build', then install it on your
      device/emulator.

   3. Launch your application.

   4. Run 'ndk-gdb' from your application project directory.

You will get a gdb prompt. See the GDB User Manual for a list of useful
commands.
Comments