android--JNI (转)
The JNI is designed to handle situations where you need to combine Java applications with native code. As a two-way interface, the JNI can support two types of native code: native libraries and native applications.
JNI就是让Java代码与native代码(比如C和C++)交互的一种机制。
《The JNI Programmer's Guide and Specification》
--http://java.sun.com/docs/books/jni/html/intro.html#994
首先编辑一个Java文件Prompt.java
public class Prompt { private native String getLine(String prompt); public static void main(String[] args) { Prompt p = new Prompt(); String input = p.getLine("Type a line: "); System.out.println("User typed: " + input); } static { System.loadLibrary("Prompt"); }}javac Prompt.javajavah -jni Prompt
#include <stdio.h>#include <jni.h>#include "Prompt.h"JNIEXPORT jstring JNICALL Java_Prompt_getLine(JNIEnv *env, jobject obj, jstring prompt) { char buf[128]; const jbyte *str; str = (*env)->GetStringUTFChars(env, prompt, NULL); if (str == NULL) { return NULL; } printf("%s", str); (*env)->ReleaseStringUTFChars(env, prompt, str); scanf("%s", buf); return (*env)->NewStringUTF(env, buf);}gcc -shared -fPIC -I /opt/java/include/ -I /opt/java/include/linux/ Prompt.c -o libPrompt.so
java -Djava.library.path=. Prompt