2015年4月1日 星期三

[Android] How to call Native C/C++ functions by JNI mechanism? - part I

Basically, the APIs provided by Android can fulfill most requirements for our coding.
However, we may need to access the native C/C++ functions directly.
Maybe it is for the performance issue, or just for that the functions Android provided are not enough.

If you use Eclipse like me, then you need to install CDT and NDK for your Eclipse.
After that, right-click the mouse on the project which you want to add the JNI interface.
Select the item "Android Tools"/"Add Native Support".
You will find that a new folder "jni" is added in the proejct.
There have one file "x.cpp" and another one "Android.mk".
We have finished the first step so far.

Next, how the Jave program calls JNI functions?
package myTest.com;
 
import android.app.Activity;
import android.os.Bundle;
 
public class MainActivity extends Activity {

hello("my Test");

private native String hello(String s); 
 
 static {
  System.loadLibrary("NativeMyTest");
 } 
}
"NativeMyTest" is the name you entered when you add the "jni" folder as mentioned before.
It will generate "NativeMyTest.so" later.
hello(String s) is the function defined in JNI.

In JNI part:
#include <jni.h>
#include <stdio.h>

 #define LOG_TAG "MainActivity"
#define LOGI(...) __android_log_print(4, LOG_TAG, __VA_ARGS__);

JNIEXPORT void hello(JNIEnv* env, jobject obj, jstring str){ 
 LOGI("hello: %s", str);
}

jint JNI_OnLoad(JavaVM* pVm, void* reserved) {
  JNIEnv* env;
  if ((*pVm)->GetEnv(pVm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) {
  return -1;
  }
 
  JNINativeMethod nm[2];
  nm[0].name = "hello";
  nm[0].signature = "(Ljava/lang/String)V";
  nm[0].fnPtr = (void*)hello;

  jclass cls = (*env)->FindClass(env, "myTest/com/MainActivity");
  (*env)->RegisterNatives(env, cls, nm, 1);
  gJavaVM = pVm;
  return JNI_VERSION_1_6;
}
JNI_OnLoad() is used to load those functions which will be called in Java program.
The parameter in FindClass() need to be the same as the names of Java package and class.

沒有留言:

張貼留言