Hello JNI

The Java Native Interface defines a standard naming and calling convention so the Java virtual machine can locate and invoke native methods. In fact, JNI is built into the Java virtual machine so the Java virtual machine can invoke local system calls to perform input and output, graphics, networking, and threading operations on the host operating system.

Please follow the following steps to get a basic knowledage about JNI. (my os is Linux)

step 1: Create a java file named Hello.java

class HelloJni
{
        public static native void sayHello();
}
step2: Compile the HelloJni.java using javac
javac HelloJni.java
check the contain of this folder, you will find that a HelloJni.class is generated.


step3: Generate a head file using javah

javah HelloJni
Check the folder again, you'll find that a HelloJni.h is generated:

Now, open the HelloJni.h with vi editor, you can find it's contain is:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloJni */

#ifndef _Included_HelloJni
#define _Included_HelloJni
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloJni
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloJni_sayHello
  (JNIEnv *, jclass);
step4: create a source file named HelloJni.c whose contain is:
#include <stdio.h>
#include "HelloJni.h"

JNIEXPORT void JNICALL Java_HelloJni_sayHello
  (JNIEnv *env, jclass cl)
{
        printf("Hello Jni^_^\n");
}
step5: compile HelloJni.c into a *.so file using gcc
gcc -fPIC -I /usr/lib/jvm/java-6-sun/include -I /usr/lib/jvm/java-6-sun/include/linux -shared -o libHelloJni.so HelloJni.c
and then, check the folder again you will find a so file is generated:

step6: create a HelloJniTest.java to test it:

public class HelloJniTest
{
        public static void main(String[] args)
        {
                HelloJni.sayHello();
        }

        static
        {
                System.loadLibrary("HelloJni");
        }
}

step7: run HelloJniTest using the following command:

java -Djava.library.path=. HelloJniTest
you'll see the output:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值