您的位置:首页 > 其它

JNI 实践

2013-12-25 13:14 375 查看
安装环境 vs2008 eclipse JDK1.6

java 类

第一步:java类

package JNI;

public class Sample1 {
public native int intMethod(int n);
public native boolean booleanMethod(boolean bool);
public native String stringMethod(String text);
public native int intArrayMethod(int[] intArray);
public static void main(String[] args) {
System.loadLibrary("Sample1");
Sample1 sample = new Sample1();
int square = sample.intMethod(5);
boolean bool = sample.booleanMethod(true);
String text = sample.stringMethod("JAVA");
int sum = sample.intArrayMethod(new int[] { 1, 1, 2, 3, 5, 8, 13 });
System.out.println("intMethod: " + square);
System.out.println("booleanMethod: " + bool);
System.out.println("stringMethod: " + text);
System.out.println("intArrayMethod: " + sum);
}

}

第二步编译产生class文件
\myTools\src\JNI> javac Sample1.java

第三步产生头文件

\myTools\bin> javah -classpath ./ JNI.Sample1

第4步 使用c++实现 头文件中的方法

#include "JNI_Sample1.h"

#include <stdio.h>

#include <string.h>

JNIEXPORT jint JNICALL Java_JNI_Sample1_intMethod

  (JNIEnv *env, jobject obj, jint num) {

   return num * num;

}

JNIEXPORT jboolean JNICALL Java_JNI_Sample1_booleanMethod

   (JNIEnv *env, jobject obj, jboolean boolean) {

   return !boolean;

}

JNIEXPORT jstring JNICALL Java_JNI_Sample1_stringMethod

   (JNIEnv *env, jobject obj, jstring string) {

     const char *str = env->GetStringUTFChars(string, 0);

     char cap[128];

     strcpy(cap, str);

     env->ReleaseStringUTFChars(string, str);

     return env->NewStringUTF(strupr(cap));

}

JNIEXPORT jint JNICALL Java_JNI_Sample1_intArrayMethod

   (JNIEnv *env, jobject obj, jintArray array) {

     int i, sum = 0;

     jsize len = env->GetArrayLength(array);

     jint *body = env->GetIntArrayElements(array, 0);

     for (i=0; i<10;i++)

     {   sum += body[i];

     }

     env->ReleaseIntArrayElements(array, body, 0);

     return sum;

}

准备工作

注册vs2008的cl命令
   call "%VS90COMNTOOLS%"vsvars32.bat

复制JDK下的三个头文件 到 vs2008安装目录

jdk1.6.0_10\include\jni.h

jdk1.6.0_10\include\win32\jawt_md.h

jdk1.6.0_10\include\win32\jni_md.h

C:\Program Files\Microsoft Visual Studio 9.0\VC\include

第5步执行 cl  -LD Sample1.cpp -FeSample1.dll

然后把 生成的dll库放到eclipse的工程根目录下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: