虽然java已经能够帮我们做了很多事情,几乎大部分的东西现在都可以用java来编写,但是有很多时候,用c++能够更好的实现系统的一些功能,因此,在java中调用c++编写的东西就显得十分的必要。这边文章将为你介绍用java调用vc++编写的工程的dll文件。
1.。编写java的类,这个类中System.loadLibrary()是加载动态链接库,SallyDLL是由c++产生的文件,等下将有介绍,
public native int add(int num1, int num2);是一个声明的方法,该方法的实现是由c++完成的,在java中可以跟一般
的方法一样调用。
- package testJNI.test;
- public class TestDLL
- {
- static
- {
- System.loadLibrary("SallyDLL");
- }
- public native int add(int num1, int num2);
- }
使用命令:javah -classpath . -jni testJNI.test.TestDLL
这时会生成.h文件:testJNI_test_TestDLL.h
.h文件内容如下:
- /* DO NOT EDIT THIS FILE - it is machine generated */
- #include <jni.h>
- /* Header for class testJNI_test_TestDLL */
- #ifndef _Included_testJNI_test_TestDLL
- #define _Included_testJNI_test_TestDLL
- #ifdef __cplusplus
- extern "C" {
- #endif
- /*
- * Class: testJNI_test_TestDLL
- * Method: testOutput
- * Signature: (II)I
- */
- JNIEXPORT jint JNICALL Java_testJNI_test_TestDLL_add
- (JNIEnv *, jobject, jint, jint);
- #ifdef __cplusplus
- }
- #endif
- #endif
注:将testJNI_test_TestDLL.h copy到工程下
将jdk/include下的jniport.h copy到工程下
将jdk/include下的jni.h copy到VC++安装目录下的include 如C:/Program Files/Microsoft Visual Studio 9.0/VC/include 下面
4..编写add方法的实现,新建testDll.cpp 代码如下:
- #include "stdafx.h"
- #include "testJNI_test_TestDLL.h"
- JNIEXPORT jint JNICALL Java_testJNI_test_TestDLL_add
- (JNIEnv * env, jobject obj, jint num1, jint num2)
- {
- return num1 + num2;
- }
6..测试,编写java测试代码 在java中调用c++
- public class TestDLLMain
- {
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- // TODO Auto-generated method stub
- TestDLL test = new TestDLL();
- System.out.println(test.add(20, 30));
- }
- }
通过上面的方法就实现了java调用c++编写的东西