Here are the steps:
1.) Create Android.mk in the project's "jni" folder:
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := main_jni LOCAL_CFLAGS := LOCAL_SRC_FILES := main.cpp LOCAL_LDLIBS := include $(BUILD_SHARED_LIBRARY)
2.) Create main.cpp in the "jni" folder:
#include <jni.h> using namespace std; #ifdef __cplusplus extern "C" { #endif class Test { public: Test(){}; ~Test(){}; int SomeFunc() { return 5; } }; jint Java_com_example_activity_MainActivity_SomeFunc(JNIEnv *env, jobject thiz) { Test *test = new Test(); return test->SomeFunc(); } #ifdef __cplusplus } #endif
3.) Add a call to load the library in your calling activity (MainActivity.java in this example):
static { System.loadLibrary("main_jni"); }
4.) Define the native function in the calling activity:
native int SomeFunc();
5.) Call it from the activity:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView text = (TextView) this.findViewById(R.id.text); text.setText(String.valueOf(SomeFunc())); }
6.) Run the "ndk-build" command from the project's root folder (Note: refresh the project in Eclipse after this step)
7.) Re-build and run the application