Java uses JNA to invoke C # DLLs

Source: Internet
Author: User

First, demand elaboration:

If our project takes advantage of C # development and needs to work with the Java group in the late stages of development, with some of the business logic leveraging C # already code completed, then we might consider using Java to invoke the ready-made C#dll implementation requirements. The first few days of work on the right encounter such a problem, so write down the development process.

Of course, this is just a hypothesis, specific analysis, the individual think the refactoring code is king ...

Second, the principle explanation:

In fact, I did not understand the specific principle of understanding, I would like to say, according to their own, to stimulate.

Because C # code is hosted on the. NET platform, Java cannot invoke C # code directly, so it introduces C + + middleware, and C + + projects can set the project as CLR public runtime, thereby invoking C # corresponding methods by reference. And JNA is able to directly invoke C + + generated DLL, so the general process will go through. C + + calls write good C#dll,java again call C + + generated DLL middleware, the approximate process is like this, but there are many pits, I will elaborate below.

Third, the operating platform:

System: Windows Ten x64

Development tools: Visual Studio 2015/2017 (I have implemented different versions of my Notebook and company PC) MyEclipse2014

Sdk:jdk-x86, jdk-x64 (DLL is divided into x86 and x64 platform, and JDK version to correspond, the same computer installed two versions of the JDK more annoying, I use the system configuration jdk32 bit debug 32-bit DLL, Then myeclipse with 64-bit JDK debug 64-bit DLL)

Iv. Preparatory work:

1, first prepare the above operating platform, it is recommended to choose a JDK with the same number of system bits (install VS, myeclipse or Eclipse or STS);

2. Download Jna.jar: JNA Download (download Jna-4.4.0.jar and jna-platform-4.4.0)

V. Start code

5.1 Generating C#dll

5.1.1 Start vs as Administrator (Project involves registering COM components, must be started by administrator to complete), New C # project

  

5.1.2 setting up C # projects

First, right-click on the properties of the newly created Invoke project.

Continue to set project properties.

Remember to save.

Then create a new CSharp class code that needs to be called. Here we create a few simple methods, in order to demonstrate the effect of we separately on the int, string, bool operation.

Then right-click the project and tap Generate.

First step, finish, good job.

5.2 Generating C + + middleware

5.2.1 Creating a new C + + project and setting properties

      

Project new success, right-click Project, select Properties.

  

  

5.2.2 Writing C + + code

Add CPP File

      

      

Edit CPP File

        

/**********************************2017-9-5 21:02:51 declares a method that needs to be called by Java, which maintains a consistent pre-processing statement with the Java interface method to expose the function for external invocation.  /#ifdef MYLIBAPI #else #define MYLIBAPI extern "C" __declspec (dllimport) #endif Mylibapi int add (int a, int b); Add function declaration Mylibapi char* getString (char* str); MYLIBAPI int reverse (int flag), using namespace System;using namespace invoke;//using namespace system::runtime::i Nteropservices::mint Add (int a, int b) {Method ^method = Gcnew method (); int result = Method->add (A, b); return result;} char* getString (char* str) {string ^ Parastr = gcnew String (str); Method ^method = Gcnew method (); String ^resultstring = method->getstring (PARASTR); char* result = (char*) (void*) System::runtime::interopservices:: Marshal::stringtocotaskmemansi (resultstring); return result;} int reverse (int flag) {Method ^method = Gcnew method (); int result = Method->reverse (flag); return result;} 

OK, C + + and C # All work is done, right-click Generate.

Copy the full name of the DLL generated file under Java for a while.

Vi. writing Java code

6.1 Create a new Java project, and pay attention to choosing a JDK that is consistent with the DLL platform. The two jna jars that were previously downloaded are then loaded into the project,

6.2 Start writing Java code

Package Com.dyi.test;import Com.sun.jna.library;import com.sun.jna.native;/** * requires the introduction of Jna-4.4.0.jar and  jna-platform-4.4.0 * Package: Https://github.com/java-native-access/jna * @author Stagebo * */public class Invoketest {/** * Call example * @param args * @throws Exception */public static void Main (string[] args) throws Exception {System.out.println (system.ge Tproperty ("java.version"));//output current JDK version number System.out.println (System.getproperty ("Sun.arch.data.model"));// Outputs the platform used by the current jdk CLibrary1 clib = clibrary1.instance; SYSTEM.OUT.PRINTLN ("Test results returned:" +clib.add (13, 13)); SYSTEM.OUT.PRINTLN ("Test returns Result:" +clib.getstring ("This is Java param.")); SYSTEM.OUT.PRINTLN ("Test returns Result:" +clib.reverse (True));}} /** * required interfaces, must contain instance instances and method declarations that need to be called. * @author Stagebo * */interface CLibrary1 extends Library {CLibrary1 INSTANCE = (CLibrary1) native.loadlibrary ("D:\\vs wor Kplace\\java Call Csdll Example \\x64\\Release\\CppDll ", clibrary1.class);/* The method that needs to be called, the method name is the same as the C + + method name */int Add (int a,int b); String getString (String a); Boolean reverse (Boolean flag);

Then we run:

Oh, error "Invalid memory Access", because Java found C++dll, but did not find C # DLL, where C++dll we write the full path name, can be directly found, then C # dll how to find it. The answer is to copy the C # DLL to the JDK's Bin directory, and the JVM can find it.

We copy the Invoke.dll to the bin directory of the JDK:

  

And then run:

    

nice! For the common type of int, string, Boolean can be passed smoothly, in fact, other types of can also be implemented, as long as the different types of language to follow the corresponding relationship between the type can be, the specific type of relationship can be Baidu.

    

VII. Matters of attention

7.1 Java error: Exception in thread "main" Java.lang.Error:Invalid memory access

Possible causes:

1, C#dll not copied to the JDK bin directory;

2, the data type between Java and C + + does not correspond;

7.1.2 Java error: Exception in thread "main" java.lang.UnsatisfiedLinkError:Unable to load library ' D:\vs Workplace\x86invoke Test\release\x86cppdlls ': Native library (Win32-x86/d:\vs workplace\x86invoketest\release\x86cppdlls.dll) not found in Resource path ([file:/g:/my%20eclipse%20workplace/invokecsharpx86test/bin/, file:/g:/my%20eclipse%20workplace/ Invokecsharpx86test/lib/jna-4.4.0.jar, file:/g:/my%20eclipse%20workplace/invokecsharpx86test/lib/ Jna-platform-4.4.0.jar])

Possible causes:

1, C++dll path is not correct, it is recommended to do test with absolute path, so you in C + + project after compiling without copy can be directly in the Java program call;

2, JDK Platform and C + + project platform does not match, JDK is 32 bit so c++dll must also be 32 bit, 64 bit also;

7.1.3 WINDOWS64 bit under the compiled 32-bit DLL test failed, temporarily unclear is not the reason for the 64-bit system, because my computer virtual machine is not installed on the 32-bit system to test.

Java uses JNA to invoke C # DLLs

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.