现在的位置: 首页 > 综合 > 正文

java 调用C++

2014年02月06日 ⁄ 综合 ⁄ 共 1075字 ⁄ 字号 评论关闭

首先确保环境变量设置正确。

(1)首先是在java中需要完成的工作

testdll.java

public class testdll
{
static
{
   try{
	   System.loadLibrary("goodluck");
	   }
   catch(Exception e){
	   
   }
}
public native static int get();

public native static void set(int i);

public static void main(String[] args){
	testdll test = new testdll();
	test.set(10);
	System.out.println(test.get());
	}
}

在cmd下先用javac把testdll编译成.class。再javah生成testdll.h

testdll.h文件

/* DO NOT EDIT THIS FILE - it is machine generated */
#include "jni.h"
/* Header for class testdll */

#ifndef _Included_testdll
#define _Included_testdll
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     testdll
 * Method:    get
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_testdll_get
  (JNIEnv *, jclass);

/*
 * Class:     testdll
 * Method:    set
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_testdll_set
  (JNIEnv *, jclass, jint);

#ifdef __cplusplus
}
#endif
#endif

(2)编写dll(网上好多教程)

打开vc创建win32控制台程序时在向导中选择dll。

首先在jdk的include文件夹中找到jni.h和jni_md.h放到工程的目录下。再添加testdll.h

对testdll.h的实现testdll.cpp

#include "stdafx.h"
#include "testdll.h"

int i = 0;
JNIEXPORT jint JNICALL Java_testdll_get(JNIEnv *, jclass)
{
	return i;
}
JNIEXPORT void JNICALL Java_testdll_set
(JNIEnv *, jclass, jint j)
{
	i=j;
}

编译后。把生成的dll和.class放在一起。在cmd下java testdll就行了。

【上篇】
【下篇】

抱歉!评论已关闭.