随笔-10  评论-36  文章-6  trackbacks-0
JAVA可以通过JNI接口访问本地的动态连接库,从而扩展JAVA的功能。使用JAVA JNI接口主要包括以下步骤:
(1)编写JAVA代码,注明要访问的本地动态连接库和本地方法;
(2)编译JAVA代码得到.class文件;
(3)使用javah -jni 生成该类对应的C语言.h文件;
(4)使用C/C++实现(3)生成的.h文件中声明的各函数;
(5)编译C/C++实现代码生成动态连接库。
本文使用一个简单的helloWorld示例演示JNI的使用。

(1)编写JAVA代码
public class helloWorld
{
    public native void SayHello(String name);

    static
    {
        System.loadLibrary("examdll");
    }

    public static void main(String [] argv)
    {
        helloWorld hello = new helloWorld();
        hello.SayHello("myName");
    }
}

(2)编译JAVA代码

javac helloWorld.java

(3)生成实现函数头文件

javah -classpath . helloWorld

得到的文件内容如下:

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

#ifndef _Included_helloWorld
#define _Included_helloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     helloWorld
 * Method:    SayHello
 * Signature: (Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_helloWorld_SayHello
  (JNIEnv *, jobject, jstring);


#ifdef __cplusplus
}
#endif
#endif

(4)在VC中实现上述函数

#include "helloWorld.h"
#include <stdio.h>
#include <string.h>
void JNICALL Java_helloWorld_SayHello(JNIEnv * env, jobject obj, jstring str)
{
    jboolean  b  = true;
    char s[80];
    memset(s, 0, sizeof(s));
    strcpy_s(s ,(char*)env->GetStringUTFChars(str, &b));
    printf("Hello, %s", s);
    env->ReleaseStringUTFChars(str , NULL);
}

**** 这是JNI的关键:通过env我们可以使用JAVA提供的一组函数操作与转换函数传递的参数。

(5)编译VC项目得到动态连接库 examdll.dll。

===================================
附:如何操作与返回JAVA的参数与类型,这篇文章有些实际的例子可供参考:
http://blog.sina.com.cn/s/blog_548cc485010005ct.html


posted on 2008-02-11 13:29 飞鹰 阅读(30543) 评论(2)  编辑  收藏

评论:
# re: JAVA JNI 使用实例 2013-03-01 13:34 | ee
eeeeee  回复  更多评论
  
# re: JAVA JNI 使用实例 2013-04-07 09:10 | dads
类名  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: