使用eclipse创建一个工程,在工程下建立一个类TestNative.java,其中编写了4个native方法,这4个方法使用c++实现。TestNative.java代码如下:
public class TestNative{
private native int add(int x,int y);
private native int subtract(int x,int y);
private native int multi(int x,int y);
private native int divide(int x,int y);
static {
System.loadLibrary("Helloworld");
}
public static void main(String[] args) {
TestNative hh = new TestNative();
int x = 60;
int y = 5;
System.out.println("x = " + x + " y = " + y);
System.out.println("x + y = " + hh.add(x, y));
System.out.println("x - y = " + hh.subtract(x, y));
System.out.println("x * y = " + hh.multi(x, y));
System.out.println("x / y = " + hh.divide(x, y));
}
}
eclipse会自动编译成class文件。
启动dos窗口,进入刚刚建立的eclipse工程的bin(或者classes)目录,通过javah –jni TestNative生成TestNative.h文件。
将%JAVA_HOME%/include/jni.h拷贝到VC6.0安装目录/VC98/Include/目录下。
进入VC6.0创建dll类型的空的工程。
创建Helloworld.h文件,将刚才生成的TestNative.h文件内容拷贝过来,在编写对应的Helloworld.cpp文件,自己编写实现如下。
TestNative.h代码如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class TestNative */
#ifndef _Included_TestNative
#define _Included_TestNative
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: TestNative
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestNative_add
(JNIEnv *, jobject, jint, jint);
/*
* Class: TestNative
* Method: subtract
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestNative_subtract
(JNIEnv *, jobject, jint, jint);
/*
* Class: TestNative
* Method: multi
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestNative_multi
(JNIEnv *, jobject, jint, jint);
/*
* Class: TestNative
* Method: divide
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestNative_divide
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
TestNative.cpp代码如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include "TestNative.h"
/*
* Class: TestNative
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestNative_add(JNIEnv *en, jobject obj, jint x, jint y)
{
return x+y;
}
/*
* Class: TestNative
* Method: subtract
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestNative_subtract(JNIEnv *en, jobject obj, jint x, jint y)
{
return x-y;
}
/*
* Class: TestNative
* Method: multi
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestNative_multi(JNIEnv *en, jobject obj, jint x, jint y)
{
return x*y;
}
/*
* Class: TestNative
* Method: divide
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestNative_divide(JNIEnv *en, jobject obj, jint x, jint y)
{
return x/y;
}
编译工程,在Debug目录下生成了Helloworld.dll,将Helloworld.dll拷贝到eclipse目录下,运行TestNative.java即可,如下图。
可以使用DllExp查看生成的dll文件中的方法是否正确,如下图,每个java方法都是以下划线开头的为正确的。