Java JNI in Linux

Source: Internet
Author: User

1. Create jnitest. Java:

Public class jnitest {
Static {
System. loadlibrary ("hello ");
}

Public native void say ();

Public static void main (string [] ARGs ){
System. Out. println ("I'm in Java ");
New jnitest (). Say ();
}
}

2. Compile jnitest. Java and generate the native header file:

Javac jnitest. Java
Javah-JNI jnitest

3. Create the hello. c file based on the function prototype in jnitest. h:

# Include <stdio. h>

# Include "jnitest. H"

Jniexport void jnicall java_jnitest_say (jnienv * ENV, jobject OBJ)
{
Printf ("I'm in C/C ++ \ n ");
}

4. To facilitate compilation, generate a MAKEFILE file:

Makefile:
. Phony: All

ALL:

Javac jnitest. Java

GCC -- shared-I/usr/lib/JVM/java-6-openjdk-i386/include hello. C-o libhello. So

5. Compile make and execute:

Java-djava. Library. Path =. jnitest

Note: If the libray path is not specified, an error is returned:

[Ancoo @ Ubuntu jnitest] $ Java jnitest
Exception in thread "Main" Java. Lang. unsatisfiedlinkerror: No hello in Java. Library. Path
At java. Lang. classloader. loadlibrary (classloader. Java: 1738)
At java. Lang. runtime. loadlibrary0 (runtime. Java: 823)
At java. Lang. system. loadlibrary (system. Java: 1028)
At jnitest. <clinit> (jnitest. Java: 4)
Cocould not find the main class: jnitest. program will exit.

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.