源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Ubuntu 使用Jni开发实例详解

  • 时间:2022-01-07 19:18 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Ubuntu 使用Jni开发实例详解
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

[b]4.编写Prompt.c文件实现具体功能:[/b]
#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);
}

[b]5. 编译动态库libPrompt.so;[/b] 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 [b]6. 运行。[/b] java Prompt 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部