Implementation of Calling C ++ code in Java

Source: Internet
Author: User

JNI is a Java Native Interface, that is, a Java Local Interface. This method can be used to call C/C ++ code, in essence, it calls the dynamic library generated by C/C ++ instead of calling the C/C ++ Code directly.

The Java code is as follows:

Public class TestJNI {

// JNI is implemented by calling the dynamic library of C/C ++ in essence, rather than directly

// Call the C/C ++ code block

Static {
System. loadLibrary ("Helloword ");

}
Public native void show ();

Public static void main (String argv ){

TestJNI test = new TestJNI ();
Test. show ();

}


}


Compile on the command line
Javac TestJNI. java

Generate the C/C ++ header file on the command line


Javah TestJNI

Note: Do not add a suffix after the file name when generating the header file.

At this time, a C/C ++ source file TestJNI. h will be generated in the place where the java source files are stored.

The following describes how to generate a dynamic C/C ++ Library:

Create a dynamic library project in VC 6.0, copy TestJNI. h to the new directory, and use # include "TestJNI. h" to find the header file generated using javah TestJNI.
Go to the include directory under the JDK directory and copy the jni. h and jni_md.h header files under the win32 Directory to the new project.


C ++ code:

# Include <iostream>

# Include "TestJNI. h"

JNIEXPORT void JNICALL Java_TestJNI_show
(JNIEnv *, jobject ){

Std: cout <"Helloword !!!! ";
}

Note: If the error message is not found during compilation, jni. h header file, open TestJNI. h. The header file will include <jni. h> change to # include "jni. h "can solve


After compilation, A. dll dynamic library file is generated under the Debug directory of the project folder and copied to the bin directory under the Java JDK directory.

Change *. dll file name to Helloword. dll

Then, run the java program java TestJNI on the console.
Successfully calls the program written in C ++ code !!!!

 

 

 

 

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.