
NDKのコードは通常、ライブラリとしてビルドし、Java側からloadして呼び出して使うが、Android.mkの記述を変更すれば実行ファイルとしてビルドすることが可能である。
実行ファイルにしてしまえば、わざわざJava側アプリから呼び出さなくても動作確認ができる。NDKコードの単体試験等で使えそうだ。
NDKのコードにmain()関数を追加
NDKのサンプルコード”hello-jni”を改造する形で紹介する。
改造元のソースコードは、NDKインストールディレクトリ\samples\hello-jni\jni\hello-jni.c にある。
(本記事では android-ndk-r8b を使用)
以下のように何のへんてつもないmain()関数を追加。
( ログ表示用に#include <android/log.h> と、#define TAG も追加している。)
ちなみにprintf()も使えるけど素直に__android_log_print()を使っておくのがよいと思われる。
#include <string.h>
#include <jni.h>
#include <android/log.h>
#define TAG "hello-jni.c"
/* This is a trivial JNI example where we use a native method
* to return a new VM String. See the corresponding Java source
* file located at:
*
* apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java
*/
jstring
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
jobject thiz )
{
return (*env)->NewStringUTF(env, "Hello from JNI !");
}
//********************************************************************************************
/**
* @brief main関数
* @author @loftkun
*
* @return int
*/
//********************************************************************************************
int main(void)
{
printf("%s() %d this is printf()\n", __FUNCTION__, __LINE__);
__android_log_print(ANDROID_LOG_DEBUG,TAG, "%s() %d this is __android_log_print()", __FUNCTION__, __LINE__);
return 0;
}
Android.mkの変更
include $(BUILD_SHARED_LIBRARY) は 共有ライブラリ生成の指定なのでこれをコメントアウトし、
include $(BUILD_EXECUTABLE) を追加した。
また、NDK用のログ関数(__android_log_printとか)を使えるように、
LOCAL_LDLIBS := -llog を追加した。
# Copyright (C) 2009 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := hello-jni LOCAL_SRC_FILES := hello-jni.c LOCAL_LDLIBS := -llog #include $(BUILD_SHARED_LIBRARY) include $(BUILD_EXECUTABLE)
実行ファイルをビルド・端末で実行
cygwinにて以下コマンドを実行。
ndk-build adb push ../libs/armeabi/hello-jni /data/local/ adb shell chmod 777 /data/local/hello-jni adb shell /data/local/hello-jni
実行結果
以下のようになった。
printf()は表示されたが、残念ながら__android_log_print()は表示されなかった。

と思ったけど、adbのログコマンドで見れるんだった。
adb logcat | grep グレップしたい文字列
