The NDK allows you to use JNI to use C/C++ code in your Java classes. So knowledge of JINI issues is essential. Nevertheless, this should get you started.
First, download the NDK. I downloaded r6b, the latest.
Then, create a C file in a new ‘jni’ directory in your projects root. And place this C file, test.c, there.
#include <jni.h>
jint Java_your_package_name_Yourclass_func(JNIEnv * env, jobject this) {
jint ret = 6;
return ret;
}
This simply returns an int. Or a ‘jini’, in the JNI world.
Note the function name is ‘Java’, followed by your project’s package name, underscores replacing dots.
The next word is the class name you’ll be calling this function in. Finally the name of the function, ‘func’ in this case.
The arguments to the function are mandatory. The first is the JNI environment that contains various helpers. And then the object that this function will be part of. Any arguments you want to pass it will go after that.
Now make a file that will specify and build this C code. It’s called Android.mk and lives in the same directory as you C source.
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := denevelltest
LOCAL_SRC_FILES := test.c
include $(BUILD_SHARED_LIBRARY)
The first line is a macro that tells the build script that the sources will be in this directory. Then CLEAR_VARS is used to remove the previous build vars.
Then we specify a *unique* name for our library. And then the source files. Finally we build the library via BUILD_SHARED_LIBRARY.
Now go into your project’s root directory. And run the ‘ndk-build’ command there. That’ll create you some shared libraries in your project root.
/dir/of/your/ndk/install/ndk-build
(Note use ‘ndk-build’ clean to remove previous builds. Useful when you make a change.)
Now in the class that you specified in the name of your C function, ‘Yourclass’ in this instance, add this code, above the method declarations:
static {
System.loadLibrary(“denevelltest”);
}
native int func();
Note we’re adding the ‘denevelltest’ library we declared in Android.mk. And we’re native keywords tells Java that this method is going to come from native code.
Now in one of our java method in that class we can call func() to retrieve our int.