继 前一篇 jni基本原理后,这里写了一个sample code,有关java String object 如何传到 jni jstring,native code 如何取得 java String object 的utf-8, unicode character,native 的utf-8, unicode character如何传到 java String等操作。
software enviroment: ubuntu 8.10+jdk 1.5,+gcc 4.3.2
1. after editing java code, compile it to class file:
javac HelloWorld.java
public class HelloWorld {
public static String java_str="Java String";
static {
System.loadLibrary("Hello");
}
public native void DisplayHello();
public native String PassToJni(String java_str);
public static void main(String[] args){
HelloWorld obj=new HelloWorld();
obj.DisplayHello();
String ret = obj.PassToJni(java_str);
System.out.println(ret);
}
}
2. to generate jni header file:
javah HelloWorld
then you will get a jni header file named HelloWorld.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */
#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloWorld
* Method: DisplayHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorld_DisplayHello
(JNIEnv *, jobject);
/*
* Class: HelloWorld
* Method: PassToJni
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_HelloWorld_PassToJni
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
3. new a c-source code file to implement the jni header file
vim helloworldImpl.c
#include <stdio.h>
#include "HelloWorld.h"
JNIEXPORT void JNICALL Java_HelloWorld_DisplayHello
(JNIEnv *env, jobject obj)
{
printf("in native code,say hello\n");
}
JNIEXPORT jstring JNICALL Java_HelloWorld_PassToJni
(JNIEnv *env, jobject obj, jstring str)
{
char buf_utf8[128]="能在别人身上找到自己的一些线索bbbbbbbbbb";
const jchar* uni_native="aaaaaa";
// jstring--> utf-8 char
const char *c = (*env)->GetStringUTFChars(env,str,0);
printf("string=%s\n",c);
printf("sizeof(char)=%d,len=%d\n",sizeof(char),(*env)->GetStringUTFLength(env,str));
(*env)->ReleaseStringUTFChars(env,str,c);
// jstring --> unicode char
const jchar *uni = (*env)->GetStringChars(env,str,0);
printf("unicode=%s\n",uni);
printf("sizeof(char)=%d,len=%d\n",sizeof(jchar),(*env)->GetStringLength(env,str));
(*env)->ReleaseStringChars(env,str,uni);
// native utf-8 char --> jstring
jstring jstr=(*env)->NewStringUTF(env,buf_utf8);
// native unicode ---> jstring
//jstring jstr=(*env)->NewString(env,uni_native,sizeof(uni_native));
return jstr;
}
4. compile c-source code to generate a share library
gcc -shared -I /usr/lib/jvm/java-1.5.0-sun-1.5.0.19/include/ helloworldImpl.c -o libHello.so
5. run java executive file linked with libHello.so library
java -Djava.library.path=. HelloWorld