範例:hello-jni
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
這個範例會引導您使用 NDK 建構小型 C/C++ 應用程式 hello-jni。您可以在 android-mk 分支版本中 ndk-samples 存放區的 hello-jni 目錄找到這個範例。
Android.mk
以下兩行程式碼提供原生來源檔案的名稱,以及要建構的共用程式庫名稱。建構系統新增 lib
前置字串和 .so
副檔名之後,建構程式庫的全名會是 libhello-jni.so
。
LOCAL_SRC_FILES := hello-jni.c
LOCAL_MODULE := hello-jni
如要進一步瞭解 Android.mk
檔案的用途和使用方法,請參閱 Android.mk。
Application.mk
這行程式碼會指示建構系統要針對哪個 CPU 和架構進行建構。在這個範例中,建構系統會針對所有支援的架構進行建構。
APP_ABI := all
如要進一步瞭解 Application.mk
檔案及其使用方法,請參閱 Application.mk。
Java 端實作
helloJNI.java
檔案位於 hellojni/src/com/example/hellojni/
中。這個檔案會呼叫函式從原生端擷取字串,然後在螢幕上顯示該字串。
原始碼包含 NDK 使用者應特別留意的三行程式碼。
下文將以使用順序 (而非編寫的順序) 展示這三行程式碼。
應用程式啟動時,這項函式呼叫便會載入 .so
檔案。
Kotlin
System.loadLibrary("hello-jni")
Java
System.loadLibrary("hello-jni");
在這個方法宣告中,native
關鍵字的作用是告知虛擬機器函式位於共用程式庫中 (亦即已在原生端實作)。
Kotlin
external fun stringFromJNI(): String
Java
public native String stringFromJNI();
Android 架構會呼叫上述步驟中載入及宣告的函式,並在螢幕上顯示字串。
Kotlin
tv.text = stringFromJNI()
Java
tv.setText( stringFromJNI() );
C 端實作
hello-jni.c
檔案位於 hello-jni/jni/
中,其中包含的函式會傳回 Java 端要求的字串。函式宣告如下:
JNIEXPORT jstring JNICALL
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
jobject thiz )
這個宣告與 Java 原始碼中宣告的原生函式對應。傳回類型 jstring
是 Java 原生介面規範中定義的資料類型,它是 Java 字串的指標,並非真正的字串。
傳回 jstring
後,接著是根據 Java 函式名稱和這個函式所在檔案的路徑傳回的函式名稱。請根據下列規則設定函式名稱:
- 在開頭加上
Java_
。
- 說明與頂層來源目錄相關的檔案路徑。
- 以底線取代正斜線。
- 刪除
.java
副檔名。
- 在最後一個底線後面加上函式名稱。
依據這些規則,這個範例使用的函式名稱是 Java_com_example_hellojni_HelloJni_stringFromJNI
。這個名稱指的是 hellojni/src/com/example/hellojni/HelloJni.java
中一個名為 stringFromJNI()
的 Java 函式。
JNIEnv*
是 VM 的指標,而 jobject
是從 Java 端傳遞的隱含 this
物件的指標。
以下這行程式碼會呼叫 VM API (*env)
,並向其傳遞傳回值 (亦即 Java 端函式要求的字串)。
return (*env)->NewStringUTF(env, "Hello from JNI !
Compiled with ABI " ABI ".");
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-26 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-26 (世界標準時間)。"],[],[],null,["# Sample: hello-jni\n\nThis sample guides you through hello-jni, a minimal\nC/C++ application built with the NDK. This sample is in the [hello-jni](https://github.com/android/ndk-samples/tree/android-mk/hello-jni) directory\nof ndk-samples repo, inside [android-mk branch](https://github.com/android/ndk-samples/tree/android-mk).\n\nAndroid.mk\n----------\n\nThe following two lines provide the name of the native source file, along\nwith the name of the shared library to build. The full name of the built\nlibrary is `libhello-jni.so`, once the build system adds the\n`lib` prefix and the `.so` extension. \n\n```\nLOCAL_SRC_FILES := hello-jni.c\nLOCAL_MODULE := hello-jni\n```\n\nFor more information about what the `Android.mk` file does, and how to use it, see\n[Android.mk](/ndk/guides/android_mk).\n\nApplication.mk\n--------------\n\nThis line tells the build system the CPU and architecture against which to build. In this\nexample, the build system builds for all supported architectures. \n\n```\nAPP_ABI := all\n```\n\nFor more information about the `Application.mk` file, and how to use it, see\n[Application.mk](/ndk/guides/application_mk).\n\nJava-side Implementation\n------------------------\n\nThe `helloJNI.java` file is located in `hellojni/src/com/example/hellojni/`. It calls\na function to retrieve a string from the native side, then displays it on the screen.\n\nThe source code contains three lines of particular interest to the NDK user.\nThey are presented here in the order in which they are used, rather than by\nline order.\n\nThis function call loads the `.so` file upon application startup. \n\n### Kotlin\n\n```kotlin\nSystem.loadLibrary(\"hello-jni\")\n```\n\n### Java\n\n```java\nSystem.loadLibrary(\"hello-jni\");\n```\n\nThe `native` keyword in this method declaration tells the\nvirtual machine that the function is in the shared library (that is, implemented on the native\nside). \n\n### Kotlin\n\n```kotlin\nexternal fun stringFromJNI(): String\n```\n\n### Java\n\n```java\npublic native String stringFromJNI();\n```\n\nThe Android framework calls the function loaded and declared in the\nprevious steps, displaying the string on the screen. \n\n### Kotlin\n\n```kotlin\ntv.text = stringFromJNI()\n```\n\n### Java\n\n```java\ntv.setText( stringFromJNI() );\n```\n\nC-side Implementation\n---------------------\n\nThe `hello-jni.c` file is located in `hello-jni/jni/`. It contains a function that\nreturns a string that [the Java side requested](#ji)). The function declaration is as\nfollows: \n\n```c++\nJNIEXPORT jstring JNICALL\nJava_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,\n jobject thiz )\n```\n\nThis declaration corresponds to the native function declared in the\nJava source code. The return type, `jstring`, is a data type defined\nin the\n[Java Native\nInterface Specification](http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html). It is not actually a string, but a\npointer to a Java string.\n\nAfter `jstring` comes the function name, which is based on the\nJava function name and the path to the file containing it. Construct it\naccording to the following rules:\n\n- Prepend `Java_` to it.\n- Describe the filepath relative to the top-level source directory.\n- Use underscores in place of forward slashes.\n- Omit the `.java` file extension.\n- After the last underscore, append the function name.\n\nFollowing these rules, this example uses the function name\n`Java_com_example_hellojni_HelloJni_stringFromJNI`. This name refers to a Java\nfunction called `stringFromJNI()`, which resides in\n`hellojni/src/com/example/hellojni/HelloJni.java`.\n\n`JNIEnv*` is the pointer to the VM, and\n`jobject` is a pointer to the implicit `this` object passed from\nthe Java side.\n\nThe following line calls the VM API `(*env)`, and passes it a return value:\nthat is, the string that the function on the Java side had requested. \n\n```c++\nreturn (*env)-\u003eNewStringUTF(env, \"Hello from JNI !\nCompiled with ABI \" ABI \".\");\n```"]]