你好,游客 登录 注册 搜索
背景:
阅读新闻

Ubuntu下使用Jni开发例子

[日期:2012-02-21] 来源:Linux社区  作者:zxglive2006 [字体:大 中 小]

1. 编写Java文件,在其中声明native方法, 并通过static 语句块加载动态链接库,示例Prompt.java代码如下:
class Prompt {
    private native String getLine(String prompt);


    public static void main(String args[]) {
        Prompt p = new Prompt();
        String input = p.getLine("Type a line: ");
        System.out.println("User typed: " + input);
    }


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


2.调用javac命令生成Prompt.class文件;
javac Prompt.java
3.调用javah命令生成Prompt.h头文件供C程序引用:
javah -jni Prompt
自动生成的头文件如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Prompt */


#ifndef _Included_Prompt
#define _Included_Prompt
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Prompt
 * Method:    getLine
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_Prompt_getLine
  (JNIEnv *, jobject, jstring);


#ifdef __cplusplus
}
#endif
#endif
4.编写Prompt.c文件实现具体功能:
#include <jni.h>
#include <stdio.h>
#include "Prompt.h"


JNIEXPORT void JNICALL
Java_Prompt_getLine(JNIEnv *env, jobject obj, jstring prompt)
{
    char buf[128];
    const jbyte *str;
    str = (*env)->GetStringUTFChars(env, prompt, NULL);
    if(str == NULL) {
        return NULL;       
    }
    printf("%s", str);
    (*env)->ReleaseStringUTFChars(env, prompt, str);
    scanf("%s", buf);
    return (*env)->NewStringUTF(env, buf);
}
5. 编译动态库libPrompt.so;
gcc -shared -fpic -I/usr/lib/jvm/java-6-sun-1.6.0.26/include -I/usr/lib/jvm/java-6-sun-1.6.0.26/include/linux Prompt.c -o libPrompt.so
6. 运行。
java Prompt

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款