With MSVC6, create a new Win32 DLL project (simple) and call it javahowto. In the same directory create a java source called JavaHowTo.java class JavaHowTo { public native String sayHello(); static { System.loadLibrary("javahowto"); } }
Compile the Java program and use javah utility to generate the JavaHowTo.h header file. javah -jni JavaHowTo In MSVC6, add the JavaHowTo.h in your project header files In the Tools - Options menu, set the include directories to include the Java JNI headers files. They are located in [jdk dir]\include and [jdk dir]\include\win32 directories In the javahowto.cpp source, add #include "JavaHowTo.h" JNIEXPORT jstring JNICALL Java_JavaHowTo_sayHello (JNIEnv *env, jobject obj) { return env->NewStringUTF("Hello world"); }
Select the Release configuration and build the project. Copy the javahowto.dll in the same directory as the java program. Create this new java program public class JNIJavaHowTo { public static void main(String[] args) { JavaHowTo jht = new JavaHowTo(); System.out.println(jht.sayHello()); } }
Compile and execute.
gzwrj(redwing),你那段代码就能调用dll了?类型怎么匹配
你可以通过实现Java的JNI(java native interface)来做到,在Think in java这本书里有详细介绍,如果你没有这本书,发个mail告诉我,我可以把电子书发给你。
In the same directory create a java source called JavaHowTo.java class JavaHowTo {
public native String sayHello();
static {
System.loadLibrary("javahowto");
}
}
Compile the Java program and use javah utility to generate the JavaHowTo.h header file. javah -jni JavaHowTo
In MSVC6, add the JavaHowTo.h in your project header files
In the Tools - Options menu, set the include directories to include the Java JNI headers files. They are located in [jdk dir]\include and [jdk dir]\include\win32 directories
In the javahowto.cpp source, add #include "JavaHowTo.h" JNIEXPORT jstring JNICALL Java_JavaHowTo_sayHello
(JNIEnv *env, jobject obj) {
return env->NewStringUTF("Hello world");
}
Select the Release configuration and build the project.
Copy the javahowto.dll in the same directory as the java program.
Create this new java program public class JNIJavaHowTo {
public static void main(String[] args) {
JavaHowTo jht = new JavaHowTo();
System.out.println(jht.sayHello());
}
}
Compile and execute.
/* NativeTest.java */
import java.lang.*;public class NativeTest {
public native boolean test();
static {
System.loadLibrary("NativeTest");
}
}
2.生成对应.h头文件
javac NativeTest.java
javah -jni NativeTest // 生成 .h 文件
应该生成下面的NativeTest.h
/*
* Class: MyNative
* Method: showParms0
* Signature: (Ljava/lang/String;IZ)V
*/
JNIEXPORT void JNICALL Java_NativeTest_test();
3.编写NativeTest.c文件
#include <stdio.h>
#include "NativeTest.h"
JNIEXPORT void JNICALL Java_NativeTest_test()
{
//...你的代码或调用
}
4.编译NativeTest.c
// cl -I你的java路径\include -I你的java路径\include\win32 -LD NativeTest.c -FeNativeTest.dll 我的java路径 F:\jdk1.3.1
cl -If:\jdk1.3.1\include -If:\jdk1.3.1\include\win32 -LD NativeTest.c -FeNativeTest.dll
编译成连接库的形式,这样就可以了
...
NativeTest n = new NativeTest();
n.test();
...