Java calls the dll dynamic library demo through JNA and generates the corresponding jar file detailed tutorial

Java calls dynamic libraries through JNA

  Write a demo program and use JNA to call the zpl dynamic library by importing the JNA jar package to complete the functions of opening the port of the zpl printer, closing the port, printing text, barcodes and QR codes.

1: Download the Jna jar package and import the jar package file into the project

  By downloading the corresponding version of the jar package file from the mvn warehouse, this project downloads the 5.5.0 jar package, and then puts the jar package into the project directory. It is very important to pay attention to the location where the jar package is stored! At first, I only placed the jar package in the root directory, which caused a NOCLASSFOUND exception when calling classes in the jna library later in the project, which troubled me for a long time. Therefore, it is important to store and import jar packages in the project in a standardized manner.
  First, create a new lib file in the root directory of the project and store the jar package in the lib folder.
Insert image description here
  Add the jar package to the build path. Right-click the jar package used and select Build Path–>Add to Build Path.
Insert image description here   At this time, there is an additional referenced libraries directory in the project directory, and the jar package just added is in this directory, so that the jar package is actually added to the project.
Insert image description here

2:Write interface class

  If you want to call the DLL dynamic library through JNA, you need to create a new interface class to export the methods of the DLL dynamic library.
  First, import a series of classes in the JNA package to load the dll dynamic library and complete the conversion of the java function and the c function method in the dynamic library and the type mapping of the corresponding formal parameter members. The specific c -> java mapping is shown in the figure below. Show.
![Insert image description here](https://img-blog.csdnimg.cn/41e50027459f4b929be07faa67a741da.pngInsert image description here

  Note that the above java methods all convert and map the functions that need to be used in the dll library into the corresponding java function methods so that the java program can call the method. If you only have the corresponding dynamic library but no source code and cannot know the methods in the dynamic library, you can use the following method to view the methods in the dll dynamic library.
Insert image description here

  The figure below is the conversion table between the corresponding c function parameter data type and java formal parameter data type.
Insert image description here

   Through the above implementation, the calling of the dll dynamic library and the conversion of the corresponding dll library functions into java methods can be completed.

Write a Demo program to implement the calling of dynamic library functions

  This requires calling the Java control class to complete the drawing of the GUI interface. The specific code is as follows. Function calls can be implemented by importing the above interface class and calling the methods of instance members in the interface class.
Insert image description here
   When calling the dll dynamic library function, you must pay attention to whether there are any errors in parameter replacement. This must be checked very carefully, otherwise there will be many problems when calling through java later. Some of them may be broken when the amount of code increases later. It is difficult to troubleshoot, so you need to check it carefully when referring to the c -> java mapping table. There are still some data type mappings that have not been mentioned yet. I will summarize the specific dynamic library call data type replacement later when I have the opportunity.

Problems that occurred in specific projects:
    When calling the print function to print text, it was found that the call was successful, but the printer did not print. Later, it was discovered that a label function needs to be added before and after the print function to set the start and end labels before normal printing can begin.
   An encoding format problem occurred when printing text and barcodes, causing the printed data to be garbled. After checking, it was found that the input data type should be changed to WString, and it could be printed successfully after the change.

package PrinterSdk;
import com.sun.jna.WString;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.UnsupportedEncodingException;
import PrinterSdk.DllUse;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import com.sun.jna.ptr.IntByReference;
public class PrinterDemo {
    
    
    private JFrame frame;
    private JTextField barcode_data;
    private JTextField qrcode_data;
    private JTextField Text;
    private JButton PrBar_btn;
    private JButton PrQr_btn;
    private JButton PrTx_btn;
    private JButton openPort_btn;
    private JButton closePort_btn;
    
    private  int port;
    
    public PrinterDemo()
    {
    
    
        initialize();
    }
    
    private void initialize()
    {
    
    
        frame=new JFrame();
        frame.setBounds(100, 100, 700, 550);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        frame.setTitle("PrinterDemo");
        
        PrTx_btn=new JButton("打印文本");
        PrTx_btn.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                // TODO Auto-generated method stub
                try {
    
    
//                    IntByReference i=new IntByReference(0);
//                    int o1=DllUse.instanceDll.OpenPortEx(0, i, 9600, 0);
                    WString data = new WString(Text.getText().toString());//.getBytes("gb18030");
//                    int s=DllUse.instanceDll.StartFormat_ZPL(100,100,10000,100);
                    int o=DllUse.instanceDll.StartData_ZPL(2000, 2000);
//                    DllUse.instanceDll.SetDefaultFont_ZPL(o1, "D".getBytes("gb18030"), 9, 5);
//                    DllUse.instanceDll.SetDataFont_ZPL("C".getBytes("gb18030"), 10000, 10000, "N".getBytes("gb18030"));
//                    DllUse.instanceDll.DataOrientation_ZPL("N".getBytes("gb18030"));
                    String data1="no.1234567";
    //                byte[] data2=data1.getBytes("gb18030");
                    int s=DllUse.instanceDll.StartFormat_ZPL(200,200,40039,40039);
                    int i1=DllUse.instanceDll.PrintData_ZPL(data);
                    DllUse.instanceDll.EndFormat_ZPL(port);
                    System.out.println("文本:"+i1+" "+s);
//                    int status=DllUse.instanceDll.GetPrintStatues_USB(0);
//                    System.out.println("打印机状态:"+status);
                } catch (Exception e1) {
    
    
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        PrTx_btn.setBounds(500, 100, 100, 80);
        frame.getContentPane().add(PrTx_btn);
        
        PrBar_btn=new JButton("打印条码");
        PrBar_btn.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                // TODO Auto-generated method stub
                try {
    
    
//                    IntByReference i1=new IntByReference(0);
//                    int o1=DllUse.instanceDll.OpenPortEx(0, i1, 9600, 0);
                    DllUse.instanceDll.DataOrientation_ZPL("N".getBytes("gb18030"));
                    WString data = new WString(barcode_data.getText().toString());
                    WString data1 = new WString("Y");
//                    byte[] data=barcode_data.getText().getBytes("gb18030");
//                    CodeType type=CodeType.CODE_39;
//                    System.out.println(type);
                    int s1=DllUse.instanceDll.StartFormat_ZPL(200,200,40039,10000);
                    int i=DllUse.instanceDll.BarCode_ZPL(data,2, 100, data1);
                    DllUse.instanceDll.EndFormat_ZPL(port);
                    System.out.println("条码:"+i);
                } catch (UnsupportedEncodingException e1) {
    
    
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                
            }
        });
        PrBar_btn.setBounds(500, 200, 100, 80);
        frame.getContentPane().add(PrBar_btn);
        
        PrQr_btn=new JButton("打印二维码");
        PrQr_btn.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                // TODO Auto-generated method stub
                try {
    
    
//                    IntByReference i1=new IntByReference(0);
//                    int o1=DllUse.instanceDll.OpenPortEx(0, i1, 9600, 0);
//                    int s1=DllUse.instanceDll.StartFormat_ZPL(10,10,100,100);
                    DllUse.instanceDll.DataOrientation_ZPL("N".getBytes("gb18030"));
                    WString data = new WString(qrcode_data.getText().toString());
//                    byte[] data=qrcode_data.getText().getBytes("gb18030");
                    int s=DllUse.instanceDll.StartFormat_ZPL(200,200,40039,10000);
                    int i=DllUse.instanceDll.QRCode_ZPL(data, "M".getBytes("gb18030"), 2, 8);
                    System.out.println("二维码:"+i+" "+s);
                    DllUse.instanceDll.EndFormat_ZPL(port);
                } catch (UnsupportedEncodingException e1) {
    
    
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        PrQr_btn.setBounds(500,300,100,80);
        frame.getContentPane().add(PrQr_btn);
        
        openPort_btn=new JButton("open port");
        openPort_btn.addActionListener(new ActionListener() {
    
        
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                // TODO Auto-generated method stub
                IntByReference i=new IntByReference(0);
                port=DllUse.instanceDll.OpenPortEx(0, i, 9600, 0);
                System.out.println("打开端口:"+port);
            }
        });
        openPort_btn.setBounds(100, 170, 100, 40);
        frame.getContentPane().add(openPort_btn);
        
        closePort_btn=new JButton("close port");
        closePort_btn.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                // TODO Auto-generated method stub
                DllUse.instanceDll.ClosePort(port);
            }
        });
        closePort_btn.setBounds(100, 270, 100, 40);
        frame.getContentPane().add(closePort_btn);
        
        Text=new JTextField();
        Text.setBounds(300,120,150,40);
        frame.getContentPane().add(Text);
        Text.setColumns(10);
        
        barcode_data=new JTextField();
        barcode_data.setBounds(300,220,150,40);
        frame.getContentPane().add(barcode_data);
        barcode_data.setColumns(10);
        
        qrcode_data=new JTextField();
        qrcode_data.setBounds(300,320,150,40);
        frame.getContentPane().add(qrcode_data);
        qrcode_data.setColumns(10);
    }
    
    public static void main(String[] args) {
    
    
            PrinterDemo window=new PrinterDemo();
            window.frame.setVisible(true);
    }
}

Insert image description here
  The javaDemo program was successfully run and the corresponding dynamic library was called successfully.

Package java program into jar file

Method 1:
Create a new MANIFEST.MF file in the project root directory.
Insert image description here
The content of the file is:
Insert image description here
  A space is required at the beginning of MAIN-CLASSK, then write the absolute name of the main class where the main method is located, and finally press Enter to leave the fourth line empty.
  Click the project file to select export, enter jar, and select JAR file.
Insert image description here
  Select the java program and third-party package you want to export, and select the location of the jar package to be exported and the name of the jar package in the JAR file field.
Insert image description here

  • Export generated class files and resources means exporting only the generated .class files and other resource files
  • Export all output folders for checked projects means exporting all folders of selected projects
  • Export java source file and resouces means that the exported jar package will contain your source code *.java. If you don’t want to leak the source code, then don’t select this option.
  • Export refactorings for checked projects includes some refactoring information files


  Then select the MANIFEST file you created and click finish.
Insert image description here
Method 2:
Choose to export the runnable jar.
Insert image description here
Insert image description here
The explanation of the library handling part is as follows:

(1)Extract required libraries into generated JAR.
Disassemble all import JARs and include them in each directory of the JAR, ex. net/org/xxx.class

(2)Package required libraries into generated JAR.
Package all import JARs in the root directory of the JAR

(3)Copy required libraries into a sub-folder next to the generated JAR.
Place all import JARs in a separate folder outside the JARs

Through the above two methods, the java program can be packaged into a jar file, and the jar file can be called through the terminal to run the program.

Guess you like

Origin blog.csdn.net/ccjjjjdff/article/details/129561807