Welcome to: SysTutorials

Java中调用本地代码

  Java中调用.dll中本地代码方法介绍:

环境:
JDK:
C:\Documents and Settings\mzq>java -version
java version “1.6.0_05″
Java(TM) SE Runtime Environment (build 1.6.0_05-b13)
Java HotSpot(TM) Client VM (build 10.0-b19, mixed mode, sharing)

本地代码编译环境:
MS Visual Studio 2008

1) 编写Java代码
示例代码如下:

public class JNITest {
public static void main (String args[]) {
if (args.length > 0) {
int x = new Integer(args[0]).intValue();
int a = new mynative().cubecal(x);
System.out.println(a);
}
}
}

 

class mynative {
public native int cubecal(int x);
static {
System.loadLibrary("mynative");
}
}

注意mynative类内容即可.

2)生成为本地方法调用的mynative.h头文件

D:\workspace_java\JNI\src>javac JNITest.java

D:\workspace_java\JNI\src>javah -jni mynative

3)编写本地代码
注意:代码扩展名一定要用.c

根据mynative.h编写

#include "jni.h"

 

int cube(int x) {
return (x*x*x);
}

JNIEXPORT jint JNICALL Java_mynative_cubecal
(JNIEnv *e, jobject o, jint x) {
return cube(x);
}

4)解决依赖关系
将$JAVA_HOME$/include/jni.h $JAVA_HOME$/include/win32/jni_md.h
及mynative.h复制到vs2008 proj目录下

5)编译生成mynative.dll

6)复制mynative.dll到存放Java项目目录中运行即可

D:\workspace_java\JNI\bin 的目录

2008-06-02 14:52 413 mynative.class
2008-06-02 14:52 719 JNITest.class
2008-06-02 15:39 7,168 mynative.dll
3 个文件 8,300 字节
2 个目录 7,816,396,800 可用字节

D:\workspace_java\JNI\bin>java JNITest 9
729

 

 

本文为此文的备份: https://www.systutorials.com/89/java-calling-native-functions-in-dll/

posted @ 2010-07-09 19:07  ericzqma  阅读(441)  评论(0编辑  收藏  举报
Welcome to: SysTutorials