使用JNI的步骤

1. 写Java类,其中定义了native方法

public class WitWrapper {

    static {
        System.loadLibrary(
witengine);
    }

    /**
     * 
@param args
     
*/
    
public static void main(String[] args) {
        
new WitWrapper().run();
    }

    private void run() {
        solve(
C:\\temp\\witlib\\problem.txt);
    }

    public native static int solve(String filename);
}

2. 在命令行下用javah生成.h文件,内容如下:

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

#ifndef _Included_XXX_witwrapper_WitWrapper
#define _Included_XXX_witwrapper_WitWrapper
#ifdef __cplusplus
extern C {
#endif
/*
 * Class:     XXX_WitWrapper
 * Method:    solve
 * Signature: (Ljava/lang/String;)I
 
*/
JNIEXPORT jint JNICALL Java_XXX_WitWrapper_solve
  (JNIEnv 
*, jclass, jstring);

#ifdef __cplusplus
}
#endif
#endif

3. 复制.h文件到一个vc++6.0的dll工程里,用vs2005得到的dll会依赖msvcr80d.dll等其他dll,不建议。把$jdk_dir$/include里的jni.h和$jdk_dir$/include/win32里的jni_md.h也添加到这个工程里。

4. 按.h文件实现.c文件对应的方法,如下例,注意jstring类型要转换成char *类型,否则即使英文也会有乱码:

/**************************************************************************** 
 *
 * Sample WIT API Program.
 * Runs implosion on the Diner problem.
 *
 ***************************************************************************
*/
#include 
<stdlib.h>
#include 
wit.h
#include 
jni.h

/****************************************************************************/
/* Main Program                                                             */
/****************************************************************************/
JNIEXPORT jint JNICALL Java_XXX_WitWrapper_solve
  (JNIEnv 
* env, jclass jc, jstring file)
{
  WitRun 
* theWitRun;
  
const char *str = (*env)->GetStringUTFChars(env, file, 0);//把jstring转换为char *,否则会有错
  printf(str);

   /* Initialize WIT */
   witNewRun( 
&theWitRun );
   witInitialize ( theWitRun );

   witReadData (theWitRun, str);
   /*************************************************************************
    *
    * Finished entering data
    *
    ***********************************************************************
*/

   witOptImplode( theWitRun );
   witWriteExecSched( theWitRun, execsched.txt, WitBSV );
   witWriteShipSched( theWitRun, 
shipsched.txt, WitBSV );

   witDeleteRun( theWitRun );

   exit (0);

/* main */
5. 编译生成.dll文件,把它和其他依赖的文件放在path环境变量包含的一个目录下,在java里就可以调用了。注意调用这个dll的java类名(包括所在包)不能改,否则会出现UnsatisfiedLinkException,如果一定要改名,只能重新生成一遍dll了。

相关帖子:
  • No Related Posts
  • micas Jun 27th 2007 11:50 am JavaBasic No Comments yet Trackback URI Comments RSS

    Leave a Reply

    You must be logged in to post a comment.