Chinaunix首页 | 论坛 | 博客
  • 博客访问: 182931
  • 博文数量: 21
  • 博客积分: 1395
  • 博客等级: 中尉
  • 技术积分: 321
  • 用 户 组: 普通用户
  • 注册时间: 2005-04-07 13:57
文章分类

全部博文(21)

文章存档

2012年(1)

2011年(4)

2010年(12)

2009年(2)

2008年(2)

我的朋友

分类: Java

2010-11-24 15:53:43


今天试了一下java native interface。记下要点,以备查用。
1.新建一个java类,比如test.java。其中要有native方法的声明,还要有一个导入本地代码的静态方法块。test.java的代码如下:

public class test
{
 static{
/*导入本地代码,此处叫test,是因为后面生成的dll文件是test.dll,(linux下为test.so)*/
 System.loadLibrary("test");
 }

 public native int add(int a,int b); //声明本地方法
 public static void main(String args[])
 {
 System.out.println(new test().add(11,22));
 }
}


2.javac test.java生成test.class,再javah -jni test生成test.h

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

#ifndef _Included_test
#define _Included_test
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class: test
 * Method: add
 * Signature: (II)I
 */

JNIEXPORT jint JNICALL Java_test_add
  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

3.在vs2005/2008中新建Visutl C++,Win32 Project,工程名test。工程类型选择dll。

4.修改工程的Property->C/C++->General->Additional Include Directories,添加jni的头文件,即添加:

D:\Program Files\Java\jdk1.6.0_22\include

D:\Program Files\Java\jdk1.6.0_22\include\win32

工程的Header Files中添加刚才生成的test.h

5.test.cpp中,实现本地方法:

#include "stdafx.h"
#include "jni.h"
#include "test.h"

JNIEXPORT jint JNICALL Java_test_add
  (JNIEnv *, jobject, jint x, jint y)
{
 return x+y;
}

6. Build 此工程,生成test.dll

7. 将test.dll复制到test.class所在目录,运行即可,java test。

阅读(589) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-11-24 20:56:31

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com