Directly on the steps:
Writing Java code
Package cn.ace.jni; Public class testnative { Public native void SayHello (); Public Static void Main (string[] args) { } } |
Use the Javah.exe tool to generate a header file cn_ace_jni_testnative.h
Build Method:
Execute the following command: Testnative is the name of the class
Generate File Contents:
/* Don't EDIT this file-it are 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 |
Write C + + code to generate a dynamic library
Create Project: MFC
Add cn_ace_jni_testnative.h to the project and copy the JDK-related files from the compile-time to the VC project directory (jni_md.h, jni.h) This file is D:\j2ee_lib\jdk1.6.0_10\include\ Directory under
Create C + + files, source.cpp content:
#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; } |
Compile the project to generate TestNative.dll
Set TestNative.dll to System environment variable (PATH): D:\testc++\testnative\debug;
Writing Java code calls a dynamic library:
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 (); } } |
Run after completion: An error appears as follows:
Cause: The environment variable you just set does not take effect, causing the path of the dynamic library to be found
Workaround: Restart Eclipse, as eclipse will load the environment variable at initial startup.
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) |
Jni--java Call c&c++