A simple JNI example

Source: Internet
Author: User

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 wocould 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.