Home Java javaTutorial Example of how Java uses jna to call dll in c#

Example of how Java uses jna to call dll in c#

Sep 08, 2017 am 10:53 AM
.net java

I took on a project some time ago, which required the use of a dll written in C# provided by a third party. The project itself is in the Java language, so the following article is written. This article introduces to you how to use jna calls in Java. The relevant information about DLL in C# is introduced in great detail through sample code. Friends in need can refer to it. Let’s take a look together.

Preface

JNA (Java Native Access) provides a set of Java tool classes for dynamically accessing the system's native library during runtime : such as Window's dll) without writing any Native/JNI code. Developers only need to describe the functions and structures of the target native library in a Java interface, and JNA will automatically map the Java interface to the native function.

Advantages

JNA allows you to call local methods directly like calling normal java methods. It is almost the same as directly executing a local method, and calling a local method does not require additional processing or configuration, nor does it require redundant references or coding, making it very convenient to use. The biggest benefit of JNA is that it avoids the time-wasting behavior of reinventing the wheel.

Everyone who has used JNI knows that JNI is a very abnormal design. JNI needs to import the code generated specifically for Java. The header file is an intrusive design, so that the forcibly modified source code compiled dll will not be called by C

#JNA description

JNA class library uses a small local class library sub to dynamically call local code. Programmers only need to use a specific Java interface to describe the structure and some basic properties of the native code method to be called. This saves a lot of configuration and compilation code to adapt to multiple platforms. Because all interfaces in the public jar package provided by JNA are called.

1. Description of requirements:

If our project is developed using c#, we will need to cooperate with the java team in the later stages of development, some of which The business logic has been code completed using C#, then we may consider using Java to call the ready-made C# dll to implement the requirements. I happened to encounter such a problem at work a few days ago, so I wrote down the development process.

Of course, this is just a hypothesis. After analyzing the specific situation, I personally think that refactoring the code is the best way...

2. Principle description:

Actually, I don’t quite understand the specific principles, so I’ll just talk about it based on my own understanding.

Because the C# code is hosted on the .net platform, Java cannot directly call the C# code, so C++ middleware is introduced. The C++ project can set the project to the clr public runtime, thereby calling C# by reference. Corresponding method. And jna can directly call the dll generated by c++, so the general process is smooth. C++ calls the written c# dll, and java then calls the dll middleware generated by c++. The general process is like this, but there are many pitfalls, which I will elaborate on below.

3. Running platform:

System: Windows 10 x64

Development tools: Visual Studio 2015/2017 (I I have implemented different versions installed on laptops and company computers) MyEclipse2014

SDK: jdk-x86, jdk-x64 (dll is divided into x86 and x64 platforms, and the version of jdk must correspond to the same computer. The two versions of jdk are quite annoying. I use the system configuration jdk32-bit to debug 32-bit dll, and then myeclipse comes with 64-bit jdk to debug 64-bit dll)

4. Preparation:

1. First prepare the above-mentioned operating platform. It is recommended to choose a jdk with the same number of digits as the system (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), you can also download it locally

5. Start CODE

5.1 Generate c#DLL

5.1.1 Start vs as administrator (the project involves registering com components, which must be started as an administrator to complete), Create a new c# project

 

 5.1.2 Set up a c# project

  First, right-click the newly created Invoke project and click Properties.

Continue setting project properties.

Remember to save.

Then create a new CSharp class code that needs to be called. Here we create some simple methods. In order to demonstrate the effect, we operate on int, string and bool respectively. As shown in the picture:

Then right-click the project and click Generate.

First step, completed, well done.

5.2 Generate c++ middleware

5.2.1 Create a new c++ project and set properties

Project, select properties.

 

## 5.2.2 Writing c++ code

Add cpp file

   

   

Edit cpp file

Okay, all the work of c++ and c# is completed, right-click to generate.

Copy the full name of the dll generated file and use it in java later.

6. Write java code

6.1 Create a new java project, and be sure to select a jdk that is consistent with the dll platform. Then load the two jna jars downloaded before into the project, as shown in the figure:

6.2 Start writing java code

Then we run:

Oh, an error was reported [Invalid Memory Access], because java found the c++dll, but did not find the c# dll. Among them, the full path name we wrote for c++dll can be found directly, so how to find the c# dll. The answer is to copy the c# dll to the bin directory of jdk, and the jvm will be able to find it.

As shown in the figure, we copy Invoke.dll to the bin directory of jdk:

 

Then run:

  

nice! Commonly used types such as int, string, and boolean can be transferred smoothly. In fact, other types can also be implemented, as long as the type correspondence between different languages ​​is followed. The specific type relationship can be found on Baidu.

7. Notes

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

Possible reasons: 1. The c#dll is not copied to the bin directory of jdk; 2. The data types between java and c++ do not correspond;

 7.1.2 java error: Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'D:\vs workplace\X86InvokeTest\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 reasons:

1. The c++dll path is incorrect. It is recommended to use the absolute path when doing tests, so that you can call it directly in the java program without copying after the c++ project is compiled;

2. JDK platform and The platform of the c++ project does not match. If jdk is 32-bit, then the c++dll must also be 32-bit, and the same is true for 64-bit;

 7.1.3 The test of 32-bit dll compiled under windows64-bit failed, it is not clear at the moment Is it because of the 64-bit system? Since the virtual machine is not installed on my computer, I did not test it on the 32-bit system.

Summarize

The above is the detailed content of Example of how Java uses jna to call dll in c#. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Java Program to insert an element at the Bottom of a Stack Java Program to insert an element at the Bottom of a Stack Feb 07, 2025 am 11:59 AM

A stack is a data structure that follows the LIFO (Last In, First Out) principle. In other words, The last element we add to a stack is the first one to be removed. When we add (or push) elements to a stack, they are placed on top; i.e. above all the

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles