java调用C++代码

一、在要使用到C++代码的类文件中声明一个native方法,例如:

1 public class TestNative{
2 
3     public native void test();
4 
5 
6 }

二、javac编译此java文件,然后使用javah TestNative命令生成一个头文件

三、使用visual studio工具新建dll项目

然后将jdk目录下的inlcude文件夹下的jni.h和jawt.h以及include/win32文件夹下的jin_md.h和jawt_md.h文件添加在上面的dll项目中,然后将我们之前生成的TestNative.h文件中的#include<jni.h>改为#inlcude"jni.h"因为引号是在本地查找头文件,

而<>实在标准库函数中查找。

 1 /* DO NOT EDIT THIS FILE - it is machine generated */
 2 #include "jni.h"
 3 /* Header for class TestNative */
 4 
 5 #ifndef _Included_TestNative
 6 #define _Included_TestNative
 7 #ifdef __cplusplus
 8 extern "C" {
 9 #endif
10 /*
11  * Class:     TestNative
12  * Method:    test
13  * Signature: (LTestNative/JavaObject;)V
14  */
15 JNIEXPORT void JNICALL Java_TestNative_test
16   (JNIEnv *, jobject);
17 
18 #ifdef __cplusplus
19 }
20 #endif
21 #endif

 

然后我们在C++中实现这个函数即可,例如:

 1 // Dll_native.cpp: 定义 DLL 应用程序的导出函数。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "TestNative.h"
 6 #include <iostream>
 7 
 8 
 9 JNIEXPORT void JNICALL Java_TestNative_test(JNIEnv *, jobject) {
10     
11     std::cout << "hello C++" << std::endl;
12 }

最后编译项目生成一个dll文件;

四、最后将生成好的dll文件放到java项目中,使用代码调用:

 1 public class TestNative{
 2 
 3     public native void test();
 4 
 5     public static void main(String[] args){
 6 
 7         System.loadLibrary("Dll_native");
 8 
 9         TestNative tn = new TestNative();
10         tn.test();
11     }
12 
13 
14 }

 

posted @ 2017-10-24 21:32  CLAYJJ  阅读(7135)  评论(0编辑  收藏  举报