Java calls a C + + dynamic-link library DLL with detailed procedures. Vs2015+eclipse and failed Solutions

Source: Internet
Author: User

background
Since I have never been in touch with Java to call C + +, we are currently considering writing the main algorithm in C + + and then invoking it in Java. By looking up the data, we find that the way to communicate, the use of JNI, that is, Java Native interface abbreviation, Chinese is "Java local calls." Functions commonly used in Java programs can call functions written in the native language, and native generally refers to functions written in C + +.
Functions in the native program can call functions in the Java layer, meaning that Java functions can be called in a C + + program. The purpose of using JNI is to mask the differences of different operating system platforms, and to invoke the native language function module through the Java language.
The blogger will demonstrate in detail how to call C++dll using Java. According to the completion, guarantee can be used.
Attach the relevant two project source code
http://download.csdn.net/detail/buptzhengchaojie/9553327
http://download.csdn.net/detail/buptzhengchaojie/9553328
I. New Java project, declaring a native method in the Java class

New Java Project

Create a packet (package) in the newly created project, and create a class under the package.

Next, add the following code to the class:

publicclass JavaInvodeCPlus {    //声明为native,表明是有外部来实现的    publicreturnHelloWorldToUpcasestring);    publicvoidsayHelloWolrd();}

Second, C + + header file that uses the Javah command to generate a declaration of the native method

Enter the location of the project where the blogger's location is D:\00Coding\my-space\JavaInvokeCPlus

Then go to the Bin directory and find a. class file that exists under the packet

We need to use the Javah command to generate the header file. Go back to the bin directory because the package name is involved, so it must be in the package directory. Press and hold the SHIFT key while you right-click inside the folder to enter the command line. Of course, you can also step into the path.

Note here that the. class suffix is not added to the end of the file. Then we can see a. h header file in the Bin directory.
Open we can see the following code:

/* Don't EDIT this file-it are machine generated * /#include <jni.h>/ * Header for class Com_cjzheng_service_javainvodecplus * /#ifndef _included_com_cjzheng_service_javainvodecplus#define _included_com_cjzheng_service_javainvodecplus#ifdef __cplusplusextern"C"{#endif/* * Class:com_cjzheng_service_javainvodecplus * method:returnhelloworldtoupcase * Signature: (ljava/lang/str ing;) ljava/lang/string; */Jniexport jstringJnicallJava_com_cjzheng_service_javainvodecplus_returnhelloworldtoupcase (JNIEnv *, Jobject, jstring);/* * Class:com_cjzheng_service_javainvodecplus * METHOD:SAYHELLOWOLRD * Signature: () V */JniexportvoidJnicallJAVA_COM_CJZHENG_SERVICE_JAVAINVODECPLUS_SAYHELLOWOLRD (jnienv *, jobject);#ifdef __cplusplus}#endif#endif

This is the content of the header file, so let's analyze the results of this header file. There is a picture of the truth:

Third, introduce the generated C + + header file to write C + + source files

Bloggers here Use the VS2015, is like to use the new software. Self-willed is also a sin ...

New Project

Click OK, then click Next to enter the following screen

Click Done to enter.

Then we need to introduce the header file has three, one is just using Javah generated header file, the remaining two need to be copied in the JDK, the blogger is using JDK7, now the three header files are copied to the C + + project directory. The JDK header file is in the JDK installation directory, and the directory for these two files is as follows:


The files for the C + + project are as follows:

Then import the three header files into the vs2015



At this time we see, looks like an error! Don't worry, people who must have learned C + + know that this is the difference between a system library and a custom library. This will change <> to ""!

And then all we need to do is implement the two methods that need to be implemented, create a new CPP file

Introduce the. h file that we generated, and then implement it.


Attached code:

#include <iostream>#include "com_cjzheng_service_javainvodecplus.h"#include <string>#include <cctype>#include <algorithm>using namespace STD;/** class:com_cjzheng_service_javainvodecplus* method:returnhelloworldtoupcase* Signature: (Ljava/lang/String ;) ljava/lang/string;*/Jniexport jstring jnicall java_com_cjzheng_service_javainvodecplus_returnhelloworldtoupcase (JNIENV *, Jobject, Jstring str) {returnSTR;}/** class:com_cjzheng_service_javainvodecplus* method:sayhellowolrd* Signature: () v*/JniexportvoidJnicall java_com_cjzheng_service_javainvodecplus_sayhellowolrd (jnienv *, Jobject) {cout<<"Hello World"<< Endl;}

Report this hint, don't panic, close on the line. As long as the bottom of the compilation is successful.

To the path of the project, we can find a DLL file generated

Iv. adding DLL files to the PATH environment variable

Here are two methods, one is to append the path to the DLL in the environment variable, and the other is to copy the DLL file to a path that already exists in path. Bloggers use the latter, because the blogger's JDK is configured with environment variables. So copy the DLL directly to the bin directory of the JDK.

So here I copy this DLL to the JDK8 path, readers do not confuse, although bloggers here to use JDK7, but that is the eclipse specified project JDK environment, can be specified, do not be confused with the environment variables.

Well, not far from the success! But the more quickly you succeed, the more tolerant you are.

load the DLL in the Java class and invoke the declarative method
Back to the Java project, write a test class, call the DLL, execute the appropriate method, you can!


Attached code:

 Public  class testmain {    /** * @Title: Testmain * @Description: TODO * @param args * void * @Date: June 18, 2016 * @author: Zhengchaojie * *     Public Static void Main(string[] args) {System.loadlibrary ("Cplusimplement");//Do not need to add a. dll suffixJavainvodecplus Javainvodecplus =NewJavainvodecplus (); System.out.println (Javainvodecplus.returnhelloworldtoupcase ("QQQQQQQ")); }}

Fortunately, successful, and without any trouble. Bingo!!!
Vi. Common Failures

1. The specified DLL file could not be found:

ExceptioninchThread"Main"Java. Lang. Unsatisfiedlinkerror: No CplusimplementinchJava. Library. PathAt Java. Lang. ClassLoader. LoadLibrary(ClassLoader. Java:1886) at Java. Lang. Runtime. LoadLibrary0 (Runtime. Java:849) at Java. Lang. System. LoadLibrary(System. Java:1088) atcom. Cjzheng. Service. Testmain. Main(Testmain. Java: -)

Solution: Verify that the DLL file name is correct, and that you have added a variable in the environment variable that can find the DLL.

2, the method name is wrong, or the number of parameters is incorrect, or the parameter is not in the form (this is the blogger another project error)

in"main" java.lang.UnsatisfiedLinkErrorcom.cjzheng.util.CPlusMethod.SAASChooseAntenna(DDDDDDDDDD)I

3, due to the different C + + compiler generated DLL on a machine, the lack of the corresponding DLL file on the B machines causes errors;

ExceptioninchThread"Main"Java.lang.unsatisfiedlinkerror:d:\program FILES\JAVA\JDK1. 8. 0_60\bin\cplusmethod.dll:can ' t find dependent libraries atJava.lang.classloader$nativelibrary.load (Native Method) atJava.lang.ClassLoader.loadLibrary1 (Classloader.java:1965) atJava.lang.ClassLoader.loadLibrary0 (Classloader.java:1890) atJava.lang.ClassLoader.loadLibrary (Classloader.java:1880) atJava.lang.Runtime.loadLibrary0 (Runtime.java:849) atJava.lang.System.loadLibrary (System.java:1088) atCom.cjzheng.util.cplusmethod.<clinit> (Cplusmethod.java: A) atCom.cjzheng.service.impl.TestMain.main (Testmain.java: +)

Here is a more convenient way to solve this problem.
For example, if a machine is VS2010, the DLL is compiled with VS2010, tested on this machine, but replaced by a device, the error is reported above. If this error is reported, the first thing to be sure is that the library path is correct. At this point, if you go to install VS2010, the problem will certainly be solved, but VS2012 is too troublesome to put up. So the workaround here is to remove the/MD option when using VS2010 to compile C + + DLLs on a machine. Specific steps:

This allows you to use the DLL without installing VS2010 on the B machine!

Java calls a C + + dynamic-link library DLL with detailed procedures. Vs2015+eclipse and failed Solutions

Related Article

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.