Chitika

Thursday, February 7, 2013

JNI NDK for android developers (and casual c programmer)

  1. Download NDK
  2. extract NDK on c drive (no space in path)
  3. create jni folder in eclipse android project, put c file(s), make file and libraries (.a/.o) in this folder
  4. c file should be as follows (lowlevelfunctions.c), note signature of function:
#include <string.h>
#include <jni.h>
#include "thirdpartylib.h"


jstring Java_com_example_LowLevelFunctions_getInfo(JNIEnv* env, jobject javaThis) {

return (*env)->NewStringUTF(env, "hello world");
}

/************************************
*** and make file as follows (Android.mk): ***
************************************/


LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := lowlevelfunctions
LOCAL_MODULE_TAGS := lowlevelfunctions
LOCAL_SRC_FILES := lowlevelfunctions.c
LOCAL_ARM_MODE := arm

LOCAL_LDFLAGS = $(LOCAL_PATH)/thirdpartylib.a
#LOCAL_STATIC_LIBRARIES := thirdpartylib

include $(BUILD_SHARED_LIBRARY)

5.  on cmd, navigate to jni folder
6. on the jni folder, execute ndk-build executable directly from NDK root path
7. liblowlevelfunctions.so will be created to the parent folder's lib folder
8. to include it in the java, note the function name in c file, it should be added in the class LowLevelFunctions of com.example package, named getInfo, as follows:

package com.example;

class LowLevelFunctions {

static {
System.loadLibrary("lowlevelfunctions"); // as defined in make file LOCAL_MODULE
}

public static native String getInfo();

}

9. If you want to create executable, include int main() function in c file and include $(BUILD_EXECUTABLE) in last line of make file.




1 comment: