Chinaunix首页 | 论坛 | 博客
  • 博客访问: 9087110
  • 博文数量: 1732
  • 博客积分: 12961
  • 博客等级: 上将
  • 技术积分: 19830
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-09 11:25
个人简介

偷得浮生半桶水(半日闲), 好记性不如抄下来(烂笔头). 信息爆炸的时代, 学习是一项持续的工作.

文章分类

全部博文(1732)

文章存档

2023年(26)

2022年(112)

2021年(217)

2020年(157)

2019年(192)

2018年(81)

2017年(78)

2016年(70)

2015年(52)

2014年(40)

2013年(51)

2012年(85)

2011年(45)

2010年(231)

2009年(287)

分类:

2009-06-16 09:03:46

一个JNI下c和java程序范例

1.编辑jprint.java文件
gliethttp@Leith:~/Android$ cat jprint.java
public class jprint
{
 /*******************************************************
 *the print() function will call the printf() funcion which is a ANSI c funciton
 ********************************************************/
    public native void print();
    static
    {
        System.loadLibrary("jnilibs");
    }
}
2.生成class和.h文件
gliethttp@Leith:~/Android$ javac jprint.java
这样会生成jprint.class
然后使用javah生成jprint.h文件
gliethttp@Leith:~/Android$ javah jprint
3.将jprint.h作为hello.c的头文件,并实现jprint.h中定义了的jni接口函数.
4.编写hello.c文件
gliethttp@Leith:~/Android$ cat hello.c
#include
#include "jprint.h"

JNIEXPORT void JNICALL Java_jprint_print(JNIEnv *env, jobject obj)
{
    printf("hello,Android!\n###Leith_gliethttp.\n");
}
5.编译jni的java共享库
gliethttp@Leith:~/Android$ gcc -fPIC -I /usr/local/jdk1.5/include -I /usr/local/jdk1.5/include/linux -shared -o libjnilibs.so *.c
6.成功后会在当前目录下生成libjnilibs.so文件,将当前libjnilibs.so所在目录加入LIB路径变量中.
gliethttp@Leith:~/Android$ export LD_LIBRARY_PATH=.:./lib:/home/gliethttp/Android:$(LD_LIBRARY_PATH)
7.编写java应用程序,调用c中的print函数
gliethttp@Leith:~/Android$ cat gliethttp_hello.java
public class gliethttp_hello
{
    public static void main(String[] args)
    {
        jprint p = new jprint();
        p.print();
    }
}
8.编译应用程序gliethttp_hello
gliethttp@Leith:~/Android$ javac gliethttp_hello.java
9.好了,一切完成了,执行看效果吧:
gliethttp@Leith:~/Android$ java gliethttp_hello
hello,Android!
###Leith_gliethttp.

PS:使用vim编辑java程序的时候,必须要注意的是,TAB按键一定要正确为^I,绝对不要用4个空格替代,否则
   javac老是提示错误,对于vim可以使用ctrl+v+tab的输入来输入一个正确的TAB键,
   可以使用:set list,:set nolist取消:).
PS1:应该这样建立目录,这样格式比较统一
|-- c_source
|   |-- hello.c
|   `-- jprint.h
|-- java
|   |-- gliethttp_hello.java
|   `-- jprint.java
|-- lib
|   `-- libjnilibs.so
文件:Andriod.tar.bz2
大小:3KB
下载:下载
阅读(2332) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~