<< Java性能-Java performance | 首页 | 配置Spring+hibernate使用ehcache作为second-level cache >>

How To Get Started Using JNA - 如何用Java调用本地dll或so库

Java Native Access (JNA) has a single component, jna.jar; the supporting native library (jnidispatch) is included in the jar file to avoid extra configuration steps. JNA is capable of extracting and loading the library on its own, so you don't need to reconfigure your native library path in any way. The native library is also available in a platform-specific jar file for use with Java Web Start.

A simple introduction to using JNA:

  1. From the download page, download jna.jar.
  2. Identify a native target library that you want to invoke from your Java code. This can be any library with exported functions, and it must be loadable from the JDK just like any native library. A good example is the local C library (libc.so on linux or msvcrt.dll on windows).
  3. Note that your target library must be available to your Java program. There are several ways to do this:
    • The path to the target library (not the jnidispatch library) may be specified by defining the jna.library.path system property, which behaves similarly to java.library.path but only applies to libraries loaded by JNA. This is the preferred method.
    • Add the path to the library to Java's java.library.path system property from the command line. For example, java -Djava.library.path=path/to/jnidispatch/lib ....
    • Change the appropriate library access environment variable. This is PATH on Windows, LD_LIBRARY_PATH on Linux, and DYLD_LIBRARY_PATH on OSX.
    • Add the libraries as extensions to your JDK installation. See the JDK documentation for details on this.
  4. Declare a Java interface to hold the native library methods by extending the Library interface. Declare methods that mirror the functions in the target library by defining Java methods with the same name and argument types as the native function. Following is an example of mapping for the Windows kernel32 library.
  5. You may also need to declare native structures to pass to your native functions. To do this, create a class that extends Structure and add public fields (which may include arrays or nested structures). You can add normal Java methods also, but they will not be used by JNA.
  6. In your interface, allocate an instance of the native library using the Native.loadLibrary(Class) method, providing the native library interface you defined in step (4).
  7. Simply invoke methods on the returned Java instance just like any other Java class. The JNA library marshals values to and from native code and invokes native functions using the jnidispatch library. For a more extensive example, see the WindowUtils and ShapedWindowDemo classes.

 

标签 : ,



发表评论 发送引用通报