免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2421 | 回复: 0
打印 上一主题 下一主题

Java native interface入门 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-06-24 21:04 |只看该作者 |倒序浏览
今天试了一下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。
TAG:
Java
JAVA
java
native文章由歌瑞尔内衣旗舰店整理,收集辛苦,希望能保留出处,谢谢斑竹大哥。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP