虽然java已经能够帮我们做了很多事情,几乎大部分的东西现在都可以用java来编写,但是有很多时候,用c++能够更好的实现系统的一些功能,因此,在java中调用c++编写的东西就显得十分的必要。这边文章将为你介绍用java调用vc++编写的工程的dll文件。


1.
。编写java的类,这个类中System.loadLibrary()是加载动态链接库,SallyDLL是由c++产生的文件,等下将有介绍,
public native int add(int num1, int num2);
是一个声明的方法,该方法的实现是由c++完成的,在java中可以跟一般
的方法一样调用。

1.     package testJNI.test;

2.      

3.     public class TestDLL

4.     {

5.         static

6.         {

7.             System.loadLibrary("SallyDLL");

8.         }

9.         

10.        public native int add(int num1, int num2);

11.    }

12.     

13.     

2..编译上面的类。我使用eclipse写的,自动编译,打开cmd,进入到java工程的bin下。
使用命令:javah -classpath . -jni testJNI.test.TestDLL
这时会生成.h文件:testJNI_test_TestDLL.h
.h
文件内容如下:
) -

1.     #include <jni.h>

2.      

3.     #ifndef _Included_testJNI_test_TestDLL

4.     #define _Included_testJNI_test_TestDLL

5.     #ifdef __cplusplus

6.     extern "C" {

7.     #endif

8.     JNIEXPORT jint JNICALL Java_testJNI_test_TestDLL_add

9.       (JNIEnv *, jobject, jint, jint);

10.     

11.    #ifdef __cplusplus

12.    }

13.    #endif

14.    #endif

15.     

3..vc++建立DLL工程,
  
注:将testJNI_test_TestDLL.h    copy到工程下
      
jdk/include下的jniport.h   copy到工程下
      
jdk/include下的jni.h    copyVC++安装目录下的include   C:\Program Files\Microsoft Visual Studio   9.0\VC\include  下面

4..
编写add方法的实现,新建testDll.cpp  代码如下:

1.     #include "stdafx.h"

2.     #include "testJNI_test_TestDLL.h"

3.      

4.     JNIEXPORT jint JNICALL Java_testJNI_test_TestDLL_add

5.       (JNIEnv * env, jobject obj, jint num1, jint num2)

6.     {

7.             return num1 + num2;

8.     }

5..Build C++工程,得到DLL文件,将文件的名改为,   SallyDLL.dll   以上面一致,并将dll文件放到jdkbin


6..
测试,编写java测试代码 java中调用c++

1.     public class TestDLLMain

2.     {

3.      

4.         

5.         public static void main(String[] args)

6.         {

7.             // TODO Auto-generated method stub

8.             TestDLL test = new TestDLL();

9.             System.out.println(test.add(20, 30));

10.        }

11.     

12.    }

13.     

14.     

可以看到输出为 50


通过上面的方法就实现了java调用c++编写的东西

posted on 2010-12-14 17:06  郄永军  阅读(1282)  评论(0)    收藏  举报