基本数据类型的传递
第一步: 编写java
public class HelloWorld{
static {
System.loadLibrary("native");
}
public native int getInt(int in);
public native boolean getBoolen(boolean bol);
public native byte getByte(byte by);
public native long getLong(long lo);
public native char getChar(char ch);
public native double getDouble(double db);
public native short getShort(short sh);
public native float getFloat(float fl);
public static void main(String[] args) {
HelloWorld world=new HelloWorld();
System.out.println("Int :"+world.getInt(10));
System.out.println("Boolen :"+world.getBoolen(false));
System.out.println("Long :"+world.getLong(10000));
System.out.println("Char :"+world.getChar('a'));
System.out.println("Double :"+world.getDouble(12.12));
System.out.println("Short :"+world.getShort((short)12));
System.out.println("Float :"+world.getFloat(10.00f));
}
}
第二步: 编译、获取,更改JNI头文件名
$ javac HelloWorld.java
$ javah HelloWorld
$ mv HelloWorld.h HelloWorld.c
第三步完成JNI文件的编写
#include <jni.h>
JNIEXPORT jint JNICALL Java_HelloWorld_getInt
(JNIEnv * env, jobject job, jint jin){
return jin*jin;
}
JNIEXPORT jboolean JNICALL Java_HelloWorld_getBoolen
(JNIEnv *env, jobject job, jboolean jb)
{
return !jb;
}
JNIEXPORT jbyte JNICALL Java_HelloWorld_getByte
(JNIEnv * env, jobject job, jbyte bt){
return bt+1;
}
JNIEXPORT jlong JNICALL Java_HelloWorld_getLong
(JNIEnv * env, jobject job, jlong jl){
return jl*jl;
}
JNIEXPORT jchar JNICALL Java_HelloWorld_getChar
(JNIEnv * env, jobject jb, jchar jc){
return jc-('a'-'A');
}
JNIEXPORT jdouble JNICALL Java_HelloWorld_getDouble
(JNIEnv * env, jobject jo, jdouble jd){
return jd*2;
}
JNIEXPORT jshort JNICALL Java_HelloWorld_getShort
(JNIEnv * jnv , jobject job, jshort js){
return js*2.0;
}
JNIEXPORT jfloat JNICALL Java_HelloWorld_getFloat
(JNIEnv * env, jobject job, jfloat jf){
return jf*2;
}
第四步: 编译
$ gcc HelloWorld.c -shared -fPIC -o libnative.so -I /usr/lib/jvm/java-7-openjdk-amd64/include/
第五步:设置程序共享库位置
$ export LD_LIBRARY_PATH=.
第六步:执行java程序
$ java HelloWorld
成功打印!
Int :100
Boolen :true
Long :100000000
Char :A
Double :24.24
Short :24
Float :20.0
下一节讲解引用数据类型的传递
网友评论