Java Invoke DLL Dynamic library method

Source: Internet
Author: User
Tags win32

jnative jar Download Address:

http://download.csdn.net/detail/heqinghua217/8865831


can also go to the official website download, the address below

http://sourceforge.net/projects/jnative/


Simple points to explain the steps:

My Windows environment is the following steps,

1, the Jnative.jar decompression, open the Lib-bin directory, find JNativeCpp.dll, put this file into the system disk, my is C disk, the path is as follows, C:\Windows\System32 under

2, put yourself to call the dynamic library, put in your designated directory, I put here is F:\\ehfscliaxdll.dll

3, import the jar into the Web project's lib directory, if not a Web project, you can put into the JDK's ext directory,

4, execute the following code: return http://Chinese 127.0.0.1:10087 to express success


The code is as follows

public static void ExeDll1 () {
try {

System.load ("F:\\ehfscliaxdll.dll");
Jnative getUrl = new Jnative ("EhfscliaxDll.dll", "GETURL");
Geturl.setretval (type.string);
Geturl.setparameter (0, "127.0.0.1");
Geturl.setparameter (1, 10087);
Geturl.setparameter (2, 123);
Geturl.invoke ();
System.out.println (Geturl.getretval ());
catch (Exception e) {
E.printstacktrace ();
}

}

--output parameters or need to define their own, such as I am the following example, 0-6 is input parameters, 7 is output parameters, to obtain output parameters, the need for black font writing

This is how it was written, the setting return value is Geturl.setretval (type.string), and the return value is: System.out.println (Geturl.getretval ()); ,

And then output a lot of logs, a bunch of errors, rewrite it now so good, and finally done,

public static void ExeDll2 () {
try {
System.load ("F:\\onlinedll.dll");
Jnative getUrl = new Jnative ("OnLineDll.dll", "onlinesign");
Geturl.setretval (type.int);/return status
Geturl.setparameter (0, 1);
Geturl.setparameter (1, "1202020709914498651");
Geturl.setparameter (2, "20150714");
Geturl.setparameter (3, "1");
Geturl.setparameter (4, "1234567890");
Geturl.setparameter (5, "79274");
Geturl.setparameter (6, "false");

Memoryblock m = memoryblockfactory.creatememoryblock (1024);
Pointer to memory block
pointer pp = new pointer (m);
Geturl.setparameter (7, pp); Output parameter
Geturl.invoke ();
System.out.println (Geturl.getretval ())//Call State
System.out.println (pp.getasstring ());//output parameter

//That's how it was written. The set return value is Geturl.setretval (type.string); Get the return value: System.out.println (Geturl.getretval ());  //, and then output a pile of logs, reported a bunch of errors, rewrite it now so good, finally finished the

Geturl.dispose ();//remember to release  



} catch ( Exception e) {
E.printstacktrace ();
}

}


------------------------------the following from http://tvjody.iteye.com/blog/125643 (he wrote well)

Because of the requirements of the project, in the Java project to invoke the Windows DLL (dynamic link library) file, before using JNI to invoke the C-write DLL file, more trouble, here is not to say, there are many online documents.

Find an open source component jnative on the Internet, and feel more convenient after use.


Get three files, respectively: Jnativecpp.dll,libjnativecpp.so,jnative.jar.
JNativeCpp.dll under Windows, copy to Windows/system32 directory;
Libjnativecpp.so under Linux, copy to the system directory;
Jnative.jar This is an expansion pack, imported into the project Lib or copied to Jdk\jre\lib\ext, the system will automatically load.

Instructions for use

My project will use the Jnative component to invoke a test application server stateTestAppSvr.dllFile, the DLL file contains aTestconnect ()Method that returns the result of an integer (1 or 0)

First configure the Windows environment for the Jnative component:
To use the native toJNativeCpp.dllPlaced on the system disk\Windows\System32Under

To import Jnative.jar into the project, create a new calling class: Java code package com.tvjody;       import java.io.file;    import java.io.fileoutputstream;    import java.io.ioexception;    import java.io.inputstream;       import org.xvolks.jnative.jnative;    import org.xvolks.jnative.type;    import org.xvolks.jnative.exceptions.nativeexception;       public class appsvrtestconnect {           public appsvrtestconnect ()  {         &nbsp                 /**         *  Test Application Server Connection status         *          *  TestConnect         *  @param  ip  Application Server Ip        *  @param  port  ports          *  @param  intrcpt   whether to use data compression method  1 :true 0:false         *  @return  int 1&nbsp: Success  0: Failure         *   @throws  NativeException        *  @throws   illegalaccessexception        */       private  static final int testconnect (STRING IP, INT PORT, INT INTRCPT) throws nativeexception, illegalaccessexception {            JNative n = null;            try {                       &NBSp;    n = new jnative ("TestAppSvr.dll",  "Testconnect");                n.setretval (Type.INT);                int i = 0;                n.setparameter (i++,  TYPE.STRING, IP);                n.setparameter (i++,  type.int,  ""  + port);                n.setparameter (i++,  type.int,  ""  + intrcpt);                n.invoke ();                return  Integer.parseint (N.getretval ());      &Nbsp;     } finally {                if  (n != null)                     n.dispose ();           &nbsp}        }        /**        *  Specify DLL file path, dynamically load local link library, test application Server connection status         * setDllPath        * @ The path to the Param path dll file, without the DLL name   for example: windows - d:\test\test\ unix - root/ test/test/        *  @param  ip  Application Server ip         *  @param  port  Ports         *  @param   intrcpt   whether data compression mode is used  1 :true 0:false        *  @return  int 1 : Success  0: Failure         *  @throws  NativeException         *  @throws  IllegalAccessException        */       public static final int testconnectfromdllpath (String path, STRING IP, INT PORT, INT INTRCPT)  throws NativeException,  illegalaccessexception{           path +=  " TestAppSvr.dll ";            system.load (path);            return testconnect (IP,PORT,INTRCPT);        }        /**         * dll files are placed under the Jre\bin directory, ClassLoaderYou can dynamically load local link libraries         * TestConnectFromDllPath  via System.loadlibrary ()        *  @param  ip  Application Server ip         *  @param  port  ports         *  @param  intrcpt    whether data compression methods  1 :true 0:false        *  @return  INT 1&NBSP: Success  0: Failure         *  @throws   nativeexception        *  @throws  IllegalAccessException         */       public static final  Int testconnectfromdllpath (STRING IP, INT PORT, INT INTRCPT)  throws  nativeexception, illegalaccessexception{            System.loadlibrary ("Testappsvr");            return testconnect (IP,PORT,INTRCPT);        }   }  
This class implements a static private method that calls the method in the DLL file to return the result

private static final int testconnect (String IP, int port, int intrcpt)

Two static public methods to load DLL files in two ways

Public static final int testconnectfromdllpath (String path,string IP, int port, int intrcpt)//path through DLL file
public static final int testconnectfromdllpath (String IP, int port, int intrcpt)//through ClassLoader

             then create a new class, call Appsvrtestconnect.java, Implementation method One call, I am the TestAppSvr.dll file and Demo.java placed in a directory &nbsp, so get Demo.java path can get TestAppSvr.dll path, The Appsvrtestconnect.testconnectfromdllpath () method is invoked to return the correct information. Method Two is already placed TestAppSvr.dll in the Jre\bin directory, It is automatically loaded when the JVM is ClassLoader, and then the DLL file can be assembled by system.loadlibrary ("Testappsvr"). Java Code public class demo {       public int getinfo ()  throws nativeexception, illegalaccessexception{                        string path=getclass (). GetResource (File.separator). GetPath ();                    path = path.substring (1,path.length ());            system.out.println (path);    // Get the path to the DLL file                          String ip =  "192.168.0.48";  //server ip             int port = 221;              //Port             int intrcpt  = 1;            //data compression mode transmission, 1 for use; 0 for no use             //Method 1  The path of the incoming DLL file             //int info =  Appsvrtestconnect.testconnectfromdllpath (PATH, IP, PORT, INTRCPT);                        //Method 2  DLL files are already placed under the Jre\bin directory       &NBsp;     int info = appsvrtestconnect.testconnectfromdllpath (ip,  PORT, INTRCPT);                         //1 for success, 0 for failure             if  (info ==  1)                system.out.println (The application server is available.) ");            else                SYSTEM.OUT.PRINTLN (the application server is not available, check that the IP address and port are correct.) ");                         return info;        }          


system.loadlibrary (): load local link library under Windows\System32 or Jre\bin or Tomcat\bin directory

system.load (): the local link library is truncated according to the specific directory, and must be an absolute path

Note

The above example works, because is an example, so there is no most design, just implemented the loading DLL file, calling DLL file method, return information.

For more information on jnative, please refer to the source program and examples of jnative.

Note that the JVM only allows a default ClassLoader to load the native library and does not provide a dedicated API to unload a loaded native library, so start the web Server independently when the project is debugged.


---------------------------------considerations: From Http://www.cnblogs.com/beastplus/p/3156080.html


jnative Usage Considerations

The company wants to be a web system that deals with devices, requiring Java to invoke DLLs. The Java colleague said Jnative looks very good, find me help to adjust the pass. With the 1.3.1 version of the environment setting.

Jnative debugging information needs to be opened to be more clear, or always say that the library did not load, and did not say the same.

System.setproperty ("Jnative.debug", "true");

If there is a system.loadlibrary () in the debug information, the JNativeCpp.dll is not loaded, and the full path is specified, with double slashes.

System.setproperty ("Jnative.loadnative", "D:\\test\\jnativecpp.dll"); LIB Library path problem windows

You need to set the calling DLL path to the environment variable path under Windows, unless you don't mind copying to Win32, DLL-dependent libraries also have to be in path or Win32. Linux

Linux also needs to set environment variables, edit BASHRC, add export ld_library=so path, rely on the library also in path, unless all placed under the/usr/lib/Lib library name problem

Whether Linux or Windows in the Jnative Constructor's Lib library name is the full name of the library, including the extension DLL, so, and so need to include the front of the ' Lib ', it seems to say is not the same as the Internet. Resource release issues

Some devices need to initialize first in operation, finally release, all functions are dispersed in different functions, jnative need to have a static instance, the Lib library is still loaded every time the call function is created.


-----------------------------------------------------------the article from http://blog.163.com/wex660@126/blog/static/ 24153065201031554358152/



Today, the use of jnative encountered a number of small problems, depressed is me, made a long time to find the location of the problem:  
Let's talk about Jnative's use first (Jnative is a jar package that encapsulates access to dynamic libraries and facilitates Java access to dynamic libraries): &NBSP
First: download jnative (http://sourceforge.net/projects/jnative/) is something sourceforge;

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.