Linux platform Java call so library-jni use example

Source: Internet
Author: User

First, write a Java file that contains the native method

public class Myjni {public    native void display ();    Public native double sum (double x, double y);    public static void Main (string[] args) {           }}
Next, compile this Java file into an. h file
Javah Myjni

After executing this command, a MyJni.h file is produced in the directory

Third, write a. c file that introduces just the header file

#include <jni.h> #include "MyJni.h" #include <stdio.h>jniexport void Jnicall java_myjni_display (jnienv *env , Jobject obj) {    printf ("Hello JNI");    return;} Jniexport jdouble jnicall java_myjni_sum (jnienv *env,jobject obj,jdouble a,jdouble b) {    return a+b;}
D. Compile the. c file into. O, and then convert to. so or. dll files
Gcc-fpic-d_reentrant-i JDK Path/jdk1.8/include-i jdk path/jdk1.8/include/linux-c myjni.c
The above command compiles the C file into an. o file.
gcc-shared Test.o-o libtest.so

The above command compiles the. o file into a. so file.


Test it in the Java method just now.

public class Myjni {    static {        system.load ("absolute path/libtest.so");    }    Use of JNI keyword Native//    this keyword determines that our methods can be used in C files    //Only declare, do not have to implement public    native void display ();    Public native double sum (double x, double y);    public static void Main (string[] args) {        Myjni myjni = new Myjni ();        System.out.print (Myjni.sum (1, 1));        System.out.print ("\ n");        Myjni.display ();    }}



Linux platform Java call so library-jni use example

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.