Java jni calls c/c ++ dll

Source: Internet
Author: User

 

Create a Test folder and create a java class Test. java. The Code is as follows:

Public class Test {

Static {

System. loadLibrary ("Test ");

}

Public native int test ();

Public static void main (String [] args ){

Test test = new Test ();

System. out. println (test. test ());

}

}

Go to cmd and enter this directory. After java Test. java is compiled, javah-jni Test generates Test. h

This is a C header file with the following content:

/* Do not edit this file-it is machine generated */

# Include <jni. h>

/* Header for class Test */

 

# Ifndef _ Included_Test

# Define _ Included_Test

# Ifdef _ cplusplus

Extern "C "{

# Endif

/*

* Class: Test

* Method: test

* Signature: () I

*/

JNIEXPORT jint JNICALL Java_Test_test

(JNIEnv *, jobject );

 

# Ifdef _ cplusplus

}

# Endif

# Endif

The preceding include <jni. h> can be changed to include "jni. h". The jni. h file is in the include folder of the jdk directory and can be copied to the current Test directory.

Then create the C code file. The Test. c code is as follows:

# Include "test. h"

 

JNIEXPORT jint JNICALL Java_Test_test

(JNIEnv * env, jobject obj)

{

Return 1;

}

Then use the cl command (cl is the C compiler compilation command) to compile Test. c. The command is as follows:

Cl-Id: \ jdk \ include \ win32-LD Test. c (myDll. lib)-FeTest. dll

(MyDll. lib) is the code library used in your C code file. In this example, it is useless and does not need to be imported. The path specified by-Id indicates the header file required by jni. h file location. -LD indicates that the dynamic link library (dll) is to be generated.

Finally, let's Test the java Test running Test. class in the Test directory.

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.