直接上步骤:
编写java代码
package cn.ace.jni;
public class TestNative {
public native void sayHello();
public static void main(String[] args) {
} } |
使用javah.exe工具生成头文件 cn_ace_jni_TestNative.h
生成方法:
执行如下命令:TestNative为class的文件名
生成文件内容:
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class cn_ace_jni_TestNative */ #ifndef _Included_cn_ace_jni_TestNative #define _Included_cn_ace_jni_TestNative #ifdef __cplusplus extern "C" { #endif /* * Class: cn_ace_jni_TestNative * Method: sayHello * Signature: ()V */ JNIEXPORT void JNICALL Java_cn_ace_jni_TestNative_sayHello (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif |
编写C++代码,生成动态库
创建工程:MFC
将cn_ace_jni_TestNative.h添加到工程中,同时将编译时所以来的jdk相关文件拷贝到VC工程目录下(jni_md.h、jni.h)此文件为D:j2ee_libjdk1.6.0_10include目录下
创建C++ 文件,source.cpp 内容:
#include"cn_ace_jni_TestNative.h" #include<iostream> using namespace std; JNIEXPORT void JNICALL Java_cn_ace_jni_TestNative_sayHello(JNIEnv * env, jobject obj) { cout<<"Hello world!"<<endl; } |
编译工程生成testNative.dll
将testNative.dll设置为系统环境变量(path):D:TestC++ estNativeDebug;
编写java代码调用动态库:
package cn.ace.jni;
public class TestNative {
public native void sayHello();
public static void main(String[] args) { System.loadLibrary("testNative"); TestNative testNative = new TestNative(); testNative.sayHello(); } } |
完成后运行: 出现错误如下:
原因:刚设置的环境变量没有生效,导致找不到动态库的路径
解决办法:重启动eclipse,因为eclipse在初次启动时,会加载环境变量。
Exception in thread "main" java.lang.UnsatisfiedLinkError: no testNative in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1709) at java.lang.Runtime.loadLibrary0(Runtime.java:823) at java.lang.System.loadLibrary(System.java:1030) at cn.ace.jni.TestNative.main(TestNative.java:8) |