AndroidNDKをつかってC言語を動かす
- Hello World的なものは出たので、次は独自コードを書いて動かしたい
環境
Android Stuido Dolphin
やっていく
方針:C言語でバブルソートを書いて処理が終わったら配列最初の数字をエミュレータに出す
とりあえずhello worldまで出せる
以下記事でとりあえずhelloworld的なものが出せるようにする
Cのファイルを作成する
cppの下でcファイルを作成
ファイル名に.cを付けてください
CMakeLists.txtを編集
ライブラリの設定をCMakeLists.txtに以下追加します
...
add_library( # Sets the name of the library.
ndktest
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
native-lib.cpp
bubble_sort.c) //<-自分の作ったファイル名を追加
...
MainActivity.ktで呼び出す
下の方に
external fun stringFromJNI(): String
とあるので、その下に関数を作る
...
external fun stringFromJNI(): String
external fun bubbleSort(): Int
...
エラーになる
赤くなるのでカーソルを当てると"Create JNI function for bubbleSort"って出てくるのでクリックして作ってもらう
Cファイル
勝手に途中まで作成してくれるので、処理を書いてください。
コードはJNIで書いてください(Java Native Interface)
JNI → Wikipedia: https://ja.wikipedia.org/wiki/Java_Native_Interface
とりあえず配列を作ってバブルソートで並び変えてもらう
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <jni.h>
JNIEXPORT jint JNICALL Java_com_example_ndktest_MainActivity_bubbleSort(JNIEnv *env, jobject thiz) {
int array[10] = {10,9,8,7,6,5,4,3,2,1};
int i, j, temp;
for (i = 0; i < 10; i++) {
for (j = i + 1; j < 10; j++) {
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array[0];
}
MainActivity.ktでbubbleSort()を呼ぶ
今回はもともと合った関数がbinding.sampleText.text
に設定されていたので、
ここをbubbleSort()にして、配列の最初のデータを表示させる。
...
// Example of a call to a native method
binding.sampleText.text = bubbleSort().toString()
...
実行
バブルソートができているので配列の一番小さい数字が表示された。
おしまい
いつもどおりxmlを変更して表示する場所を変えたりできます。
ですが、Kotlin -> C , C -> Kotlin で引数や戻り値を使うときは書き方がちょっと変わります。
Kotlin -> C へ配列を引数として渡すときは以下の記事でどうぞ