0
0

More than 1 year has passed since last update.

AndroidNDKを使ってC言語を動かす

Posted at

AndroidNDKをつかってC言語を動かす

  • Hello World的なものは出たので、次は独自コードを書いて動かしたい

環境

Android Stuido Dolphin

やっていく

方針:C言語でバブルソートを書いて処理が終わったら配列最初の数字をエミュレータに出す

とりあえずhello worldまで出せる

以下記事でとりあえずhelloworld的なものが出せるようにする

Cのファイルを作成する

cppの下でcファイルを作成
ファイル名に.cを付けてください

スクリーンショット 2023-02-28 11.19.10.png

スクリーンショット 2023-02-28 11.19.59.png

CMakeLists.txtを編集

ライブラリの設定を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

とあるので、その下に関数を作る

MainActivity.kt
...
external fun stringFromJNI(): String
external fun bubbleSort(): Int
...

エラーになる

赤くなるのでカーソルを当てると"Create JNI function for bubbleSort"って出てくるのでクリックして作ってもらう

スクリーンショット 2023-02-28 12.25.54.png

先程自分で作ったcファイルを選択
スクリーンショット 2023-02-28 12.26.12.png

Cファイル

勝手に途中まで作成してくれるので、処理を書いてください。
コードはJNIで書いてください(Java Native Interface)
JNI → Wikipedia: https://ja.wikipedia.org/wiki/Java_Native_Interface 

とりあえず配列を作ってバブルソートで並び変えてもらう

bubble_sort.c
#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()にして、配列の最初のデータを表示させる。

MainActivity.kt
...
        // Example of a call to a native method
        binding.sampleText.text = bubbleSort().toString()
...

実行

バブルソートができているので配列の一番小さい数字が表示された。
スクリーンショット 2023-02-28 12.30.07.png

おしまい

いつもどおりxmlを変更して表示する場所を変えたりできます。
ですが、Kotlin -> C , C -> Kotlin で引数や戻り値を使うときは書き方がちょっと変わります。

Kotlin -> C へ配列を引数として渡すときは以下の記事でどうぞ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0