gpt4 book ai didi

Ubuntu 使用Jni开发实例详解

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 28 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Ubuntu 使用Jni开发实例详解由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

1. 编写Java文件,在其中声明native方法, 并通过static 语句块加载动态链接库,示例Prompt.java代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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 。

自动生成的头文件如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* 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文件实现具体功能:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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 。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! 。

最后此篇关于Ubuntu 使用Jni开发实例详解的文章就讲到这里了,如果你想了解更多关于Ubuntu 使用Jni开发实例详解的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com