导航

    <#CACHE_INCLUDE_NAVBAR#>
« Oracle歸檔日誌大小的修改方法微軟公司簡介 »

Java native interface入門

2010年11月29日 SUN 0条评论 0个引用

今天試了壹下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。

 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

最近发表

Powered By Z-Blog 1.8 Arwen Build 81206