Java Native Interface 入门示例
来源:互联网 发布:安徽安广网络 编辑:程序博客网 时间:2024/06/04 19:58
鉴于网上搜到的都是基于jdk1.4或以前版本,而且本地库用的是C语言。而现在是基于C++,所以更新记录如下:
第一步:创建Java源码文件
public class Hello{
static{
System.loadLibrary("Hello");
}
public Hello(){
}
public native void sayHello(String strName);
public static void main(String[] args){
Hello hello = new Hello();
hello.sayHello("fuye");
}
}
第二步:编译
javac Hello.java
第三部:生成C++文件头
javah Hello
Hello.h文件内容如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Hello */
#ifndef _Included_Hello
#define _Included_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Hello
* Method: sayHello
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_Hello_sayHello
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
第四步:新建C++实现文件
#include "Hello.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_Hello_sayHello(JNIEnv * env, jobject arg, jstring instring){
printf("This is my first jni program/n");
}
第五步: 编译,连接成本地库
1、生成Hello.o
g++ -I /usr/local/dev/java/jdk1.5.0_16/include/ -I /usr/local/dev/java/jdk1.5.0_16/include/linux/ -c Hello.cpp
2、生成libHello.so.1.0
g++ -shared -W1,-soname,libHello.so.1 -o libHello.so.1.0 Hello.o
3、生成libHello.so(拷贝即可,在库名字前加lib)
cp libHello.so.1.0 libHello.so
第六步:设置本地库路径,不然java找不到我们的.so,依据自己的实际路径
export LD_LIBRARY_PAtH=$LD_LIBRARY_PATH:/usr/local/dev/parctice
最后运行
java Hello
- Java Native Interface 入门示例
- Android:Java Native Interface入门
- JNI (Java Native Interface) 编程示例
- JNI (java native interface)入门:为什么用JNI
- Java Native Interface
- JNI:Java Native Interface
- JNI(java native interface)
- JNI - Java Native Interface
- Java Native Interface
- Java Native Interface
- JNI:Java Native Interface
- Java Native Interface
- Java Native Interface
- Java Native Interface (JNI)
- Java Native Interface Specification
- Java Native Interface (JNI)
- JNI:Java Native Interface
- Java Native Interface笔记
- 架构设计:生产者/消费者模式 第1页:“生产者/消费者模式”介绍
- php 函数 implode explode
- Zigbee与CSS定位特性比较
- Maven配置资料(二)
- 简单权限控制管理1
- Java Native Interface 入门示例
- jQuery常用技巧
- 架构设计:生产者/消费者模式 第2页:如何确定数据单元
- 翻译:测试成熟度模型集成(TMMi)(11)
- jsp的字符问题
- 学习C++的50条忠告(转载)
- 拒绝调整的是自作聪明
- 架构设计:生产者/消费者模式 第3页:队列缓冲区
- jQuery UI插件之facebox