当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
Javanativeinterface入门
发布时间:2010/11/26 16:47:52 来源:城市学习网 编辑:ziteng
  今天试了一下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。
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved