Java calls dll dynamic link library --JNA framework

1.JNA framework

  a definition of:. JNA (Java Native Access) Framework is an open source Java framework that is SUN's leading developed, based on the classic a framework on the basis of JNI

  b action:. JNA providing a set of Java-based tools for accessing the system in dynamic operation of the local library (native library: The Window of dll) without writing Native / JNI code. Developers to describe a native library functions and structure of the target in a java interface, JNA automatically implement Java interfaces to native function mapping.

  c. introducing dependent maven

  <dependencies>

    <dependency>
      <groupId>net.java.dev.jna</groupId>
      <artifactId>jna</artifactId>
      <version>5.3.1</version>
    </dependency>
    <dependency>
      <groupId>net.java.dev.jna</groupId>
      <artifactId>jna-platform</artifactId>
      <version>5.3.1</version>
    </dependency>

    ......

  </dependencies>

 

 

2. Call the system comes with dynamic link library

public  class TestPrintf { 

    public  interface CLibrary the extends Library {
         // DLL file in the default path to the project root directory, if DLL files are stored outside the project, use the absolute path 
        CLibrary INSTANCE = (CLibrary) Native.load ( (Platform.isWindows ()? "msvcrt": "c"), CLibrary. class );
         // DLL statement will be called the method (may be multiple methods) 
        void printf (String format, Object ... args); 
    } 

    public  static  void main ( String [] args) { 
        CLibrary.INSTANCE.printf ( "the Hello, World \ n-" );
         for ( int I = 0; I <args.length; I ++ ) {
            CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
        }
    }
}

 

 

3. Call a custom dynamic-link library

  a. Create a new project in the VC2019 named TestDll1

 

 

  b. Create a header file test.h

#pragma once

#define MYLIBAPI extern "C" _declspec(dllexport) 
MYLIBAPI int sum(int a, int b);

 

 

  c. Create the source file test.cpp

#include "pch.h"
#include "test.h"
#include <stdio.h>

int sum(int a, int b) {
    return a + b;
}

 

 

  d. In the toolbar to select x64 (32 bit select x86)

 

 

  e.点击项目TestDll1,右键选择“生成”,生成dll

 

 

  f.将生成的dll放入resource中

  g.创建测试类

public class TestDll {

    public interface TestDllLib extends Library {
        // DLL文件默认路径为项目根目录,若DLL文件存放在项目外,请使用绝对路径
        TestDllLib INSTANCE = (TestDllLib) Native.load("TestDll1", TestDllLib.class);
        // 声明将要调用的DLL中的方法(可以是多个方法)
        int sum(int a, int b);
    }

    public static void main(String[] args) {
        int result = TestDll.TestDllLib.INSTANCE.sum(2, 3);
        System.out.println("result: " + result);
    }

}

 

  h.注意:运行前需要用maven执行 clean package,保证 dll 打包进 target 中,不然可能报无法找到dll的错误

 

  i.参考文档:https://blog.csdn.net/shendl/article/details/3589676

Guess you like

Origin www.cnblogs.com/vettel0329/p/11084043.html