以NDK自带hellojni为例
/* HelloJni.java中的Java code */
public class HelloJni extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* Create a TextView and set its content. the text is retrieved by
* calling a native function.
*/
TextView tv = new TextView(this);
tv.setText(stringFromJNI("jialiry"));
setContentView(tv);
}
/*
* A native method that is implemented by the 'hello-jni' native library,
* which is packaged with this application.
*/
public native String stringFromJNI(String str);
/*
* This is another native method declaration that is *not* implemented by
* 'hello-jni'. This is simply to show that you can declare as many native
* methods in your Java code as you want, their implementation is searched
* in the currently loaded native libraries only the first time you call
* them.
*
* Trying to call this function will result in a
* java.lang.UnsatisfiedLinkError exception !
*/
public native String unimplementedStringFromJNI();
/*
* this is used to load the 'hello-jni' library on application startup. The
* library has already been unpacked into
* /data/data/com.example.hellojni/lib/libhello-jni.so at installation time
* by the package manager.
*/
static {
System.loadLibrary("hello-jni");
}
}
/* hello-jni.c中的C/C++ code */
/*结果:jstring Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz, jstring jstr) { char buf[128]; const char* string=(char*)(*env)->GetStringUTFChars(env,jstr,NULL); strcpy(buf, string); strcat(buf, "同志,hello from jni"); (*env)->ReleaseStringUTFChars(env,jstr,(jbyte*)string); return (*env)->NewStringUTF(env, buf); }
jialiry同志,hello from jni
*/