天天看點

java和C的接口

第一步:聲明本地變量

例如:class NativeHello{ 
  public native void nativeHelloWorld(); 
  static{ 
    System.loodlibrary("nativeTest");//調用nativeTest.dll庫檔案 
  } 
}      
第二步:生成頭檔案

    先用javac編譯NativeHello.java,再用javah生成c的頭檔案.h檔案

第三步:生成根檔案

    指令如下:javah -stubs NativeHello (生成NativeHello.c檔案)

第四步:編寫C程式(此處假定檔案名為NativeTest.c)
#include <stdio.h> 
#include <NativeHello.h>//指第二步生成的.h檔案 
#include <stubpreamble.h>//指JDK的include下的檔案 
void Nativehello_nativeHelloWorld(struct HNativeHello *this){ 
......... 
}/      

    *函數名Nativehello_nativeHelloWorld不能任意指定,可以從javah生成的頭檔案中查到,也可用 如下方法命名:類名_本地方法名(struct H類名 *this)*/

第五步:編譯DLL檔案

    将nativeTest.c和NativeHello.c編譯成DLL庫檔案,檔案名與System.loodlibrary("nativeTest")中的檔案同名

最後講一下測試的方法,源檔案如下:
class UseNative{ 
  public static void main(String []args){ 
    NativeHello nh=new NativeHello(); 
    nh.nativeHelloWorld(); 
  } 
}