A simple JNI example

tested on CentOS 5.8

Step 1: declare a native function in the java source file 

public class AddMe{
        static {
                System.loadLibrary("hello");
        }
        public native void sum(int a, int b);
        public static void main(String[] args){
                AddMe am = new AddMe();
                am.sum(2, 5);
        }
}


Step 2: compile the java class

javac AddMe.java


Step 3: generate the c header file

javah -jni AddMe

You will find the "AddMe.h" file in the current working directory


Step 4: implement the c function "sum" (by JNI naming convention the function name would be Java_AddMe_sum)

We create a c source file called "addme.c"

#include "AddMe.h"
#include <stdio.h>

JNIEXPORT void JNICALL Java_AddMe_sum (JNIEnv *env, jobject obj, jint a, jint b){
        jint result = 0;
        result = a + b;
        printf("hello world %d\n", result);
}

Step 5: compile the c code and generate a share library "libhello.so" (it must have the name libhello so that System.loadLibrary("hello") can dynamically load the library)

gcc -fPIC -I/usr/lib/jvm/java/include -o libhello.so -shared ./addme.c

Step 6: run the java bytecode

java -Djava.library.path=. AddMe


Then you can see "hell world 7" printed on console




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值