com.sun.jna

Class Native

public final class Native extends Object

Provides generation of invocation plumbing for a defined native library interface. Also provides various utilities for native operations.

Native and Native are provided to avoid having to explicitly pass these parameters to Structures, which would require every Structure which requires custom mapping or alignment to define a constructor and pass parameters to the superclass. To avoid lots of boilerplate, the base Structure constructor figures out these properties based on its enclosing interface.

Library Loading

When JNA classes are loaded, the native shared library (jnidispatch) is loaded as well. An attempt is made to load it from the system library path using System#loadLibrary. If not found, the appropriate library will be extracted from the class path into a temporary directory and loaded from there. If your system has additional security constraints regarding execution or load of files (SELinux, for example), you should probably install the native library in an accessible location and configure your system accordingly, rather than relying on JNA to extract the library from its own jar file.

Author: Todd Fast, todd.fast@sun.com twall@users.sf.net

See Also: Library

Nested Class Summary
static classNative.DeleteNativeLibrary
For internal use only.
interfaceNative.ffi_callback
Field Summary
static intLONG_SIZE
Size of a native long type, in bytes.
static intPOINTER_SIZE
The size of a native pointer (void*) on the current platform, in bytes.
static intSIZE_T_SIZE
Size of a native size_t type, in bytes.
static intWCHAR_SIZE
Size of a native wchar_t type, in bytes.
Method Summary
static voidffi_call(long cif, long fptr, long resp, long args)
static voidffi_free_closure(long closure)
static longffi_prep_cif(int abi, int nargs, long ffi_return_type, long ffi_types)
static longffi_prep_closure(long cif, Native.ffi_callback cb)
static ClassfindEnclosingLibraryClass(Class cls)
Find the library interface corresponding to the given class.
static byte[]getBytes(String s)
Return a byte array corresponding to the given String.
static byte[]getBytes(String s, String encoding)
Return a byte array corresponding to the given String, using the given encoding.
static Callback.UncaughtExceptionHandlergetCallbackExceptionHandler()
Returns the current handler for callback uncaught exceptions.
static ClassgetCallingClass()
static longgetComponentID(Component c)
Utility method to get the native window ID for a heavyweight Java Component as a long value.
static PointergetComponentPointer(Component c)
Utility method to get the native window pointer for a heavyweight Java Component as a Pointer value.
static PointergetDirectBufferPointer(Buffer b)
Convert a direct Buffer into a Pointer.
static intgetLastError()
Retrieve the last error set by the OS.
static MapgetLibraryOptions(Class type)
Return the preferred native library configuration options for the given class.
static ClassgetNativeClass(Class cls)
static StringgetNativeLibraryResourcePath(int osType, String arch, String name)
static intgetNativeSize(Class type, Object value)
Returns the native size of the given class, in bytes.
static intgetNativeSize(Class cls)
Returns the native size for a given Java class.
static booleangetPreserveLastError()
Indicates whether the system last error result is preserved after every invocation.

static intgetStructureAlignment(Class cls)
Return the preferred structure alignment for the given native interface.
static TypeMappergetTypeMapper(Class cls)
Return the preferred TypeMapper for the given native interface.
static StringgetWebStartLibraryPath(String libName)
If running web start, determine the location of a given native library.
static longgetWindowID(Window w)
Utility method to get the native window ID for a Java Window as a long value.
static PointergetWindowPointer(Window w)
Utility method to get the native window pointer for a Java Window as a Pointer value.
static intinitialize_ffi_type(long type_info)
Returns the size (calculated by libffi) of the given type.
static booleanisProtected()
Returns whether protection is enabled.
static booleanisSupportedNativeType(Class cls)
Indicate whether the given class is supported as a native argument type.
static ObjectloadLibrary(Class interfaceClass)
Map a library interface to the current process, providing the explicit interface class.
static ObjectloadLibrary(Class interfaceClass, Map options)
Map a library interface to the current process, providing the explicit interface class.
static ObjectloadLibrary(String name, Class interfaceClass)
Map a library interface to the given shared library, providing the explicit interface class.
static ObjectloadLibrary(String name, Class interfaceClass, Map options)
Load a library interface from the given shared library, providing the explicit interface class and a map of options for the library.
static voidmain(String[] args)
Prints JNA library details to the console.
static voidregister(String libName)
When called from a class static initializer, maps all native methods found within that class to native libraries via the JNA raw calling interface.
static voidregister(NativeLibrary lib)
When called from a class static initializer, maps all native methods found within that class to native libraries via the JNA raw calling interface.
static voidregister(Class cls, NativeLibrary lib)
When called from a class static initializer, maps all native methods found within that class to native libraries via the JNA raw calling interface.
static voidsetCallbackExceptionHandler(Callback.UncaughtExceptionHandler eh)
Set the default handler invoked when a callback throws an uncaught exception.
static voidsetLastError(int code)
Set the OS last error code.
static voidsetPreserveLastError(boolean enable)
Set whether the system last error result is captured after every native invocation.
static voidsetProtected(boolean enable)
Set whether native memory accesses are protected from invalid accesses.
static LibrarysynchronizedLibrary(Library library)
Returns a synchronized (thread-safe) library backed by the specified library.
static byte[]toByteArray(String s)
Obtain a NUL-terminated byte buffer equivalent to the given String, using jna.encoding or the default platform encoding if that property is not set.
static byte[]toByteArray(String s, String encoding)
Obtain a NUL-terminated byte buffer equivalent to the given String, using the given encoding.
static char[]toCharArray(String s)
Obtain a NUL-terminated wide character buffer equivalent to the given String.
static StringtoString(byte[] buf)
Obtain a Java String from the given native byte array.
static StringtoString(byte[] buf, String encoding)
Obtain a Java String from the given native byte array, using the given encoding.
static StringtoString(char[] buf)
Obtain a Java String from the given native wchar_t array.
static voidunregister()
Remove all native mappings for the calling class.
static voidunregister(Class cls)
Remove all native mappings for the given class.
static voidupdateLastError(int e)
Update the last error value (called from native code).

Field Detail

LONG_SIZE

public static final int LONG_SIZE
Size of a native long type, in bytes.

POINTER_SIZE

public static final int POINTER_SIZE
The size of a native pointer (void*) on the current platform, in bytes.

SIZE_T_SIZE

public static final int SIZE_T_SIZE
Size of a native size_t type, in bytes.

WCHAR_SIZE

public static final int WCHAR_SIZE
Size of a native wchar_t type, in bytes.

Method Detail

ffi_call

public static void ffi_call(long cif, long fptr, long resp, long args)

ffi_free_closure

public static void ffi_free_closure(long closure)

ffi_prep_cif

public static long ffi_prep_cif(int abi, int nargs, long ffi_return_type, long ffi_types)

ffi_prep_closure

public static long ffi_prep_closure(long cif, Native.ffi_callback cb)

findEnclosingLibraryClass

static Class findEnclosingLibraryClass(Class cls)
Find the library interface corresponding to the given class. Checks all ancestor classes and interfaces for a declaring class which implements Library.

getBytes

static byte[] getBytes(String s)
Return a byte array corresponding to the given String. If the system property jna.encoding is set, its value will override the default platform encoding (if supported).

getBytes

static byte[] getBytes(String s, String encoding)
Return a byte array corresponding to the given String, using the given encoding.

getCallbackExceptionHandler

public static Callback.UncaughtExceptionHandler getCallbackExceptionHandler()
Returns the current handler for callback uncaught exceptions.

getCallingClass

static Class getCallingClass()

getComponentID

public static long getComponentID(Component c)
Utility method to get the native window ID for a heavyweight Java Component as a long value. This method is primarily for X11-based systems, which use an opaque XID (usually long int) to identify windows.

Throws: HeadlessException if the current VM is running headless

getComponentPointer

public static Pointer getComponentPointer(Component c)
Utility method to get the native window pointer for a heavyweight Java Component as a Pointer value. This method is primarily for w32, which uses the HWND type (actually void *) to identify windows.

Throws: HeadlessException if the current VM is running headless

getDirectBufferPointer

public static Pointer getDirectBufferPointer(Buffer b)
Convert a direct Buffer into a Pointer.

Throws: IllegalArgumentException if the buffer is not direct.

getLastError

public static int getLastError()
Retrieve the last error set by the OS. This corresponds to GetLastError() on Windows, and errno on most other platforms. The value is preserved per-thread, but whether the original value is per-thread depends on the underlying OS. The result is undefined if Native is false.

The preferred method of obtaining the last error result is to declare your mapped method to throw LastErrorException instead.

getLibraryOptions

public static Map getLibraryOptions(Class type)
Return the preferred native library configuration options for the given class.

See Also: Library

getNativeClass

static Class getNativeClass(Class cls)

getNativeLibraryResourcePath

static String getNativeLibraryResourcePath(int osType, String arch, String name)

getNativeSize

public static int getNativeSize(Class type, Object value)
Returns the native size of the given class, in bytes. For use with arrays.

getNativeSize

public static int getNativeSize(Class cls)
Returns the native size for a given Java class. Structures are assumed to be struct pointers unless they implement ByValue.

getPreserveLastError

public static boolean getPreserveLastError()

Deprecated: The preferred method of obtaining the last error result is to declare your mapped method to throw LastErrorException instead.

Indicates whether the system last error result is preserved after every invocation.

getStructureAlignment

public static int getStructureAlignment(Class cls)
Return the preferred structure alignment for the given native interface. See OPTION_STRUCTURE_ALIGNMENT.

getTypeMapper

public static TypeMapper getTypeMapper(Class cls)
Return the preferred TypeMapper for the given native interface. See OPTION_TYPE_MAPPER.

getWebStartLibraryPath

public static String getWebStartLibraryPath(String libName)
If running web start, determine the location of a given native library. This value may be used to properly set jna.library.path so that JNA can load libraries identified by the <nativelib> tag in the JNLP configuration file. Returns null if the Web Start native library cache location can not be determined. Note that the path returned may be different for any given library name.

Use System.getProperty("javawebstart.version") to detect whether your code is running under Web Start.

Returns: null if unable to query the web start loader.

Throws: UnsatisfiedLinkError if the library can't be found by the Web Start class loader, which usually means it wasn't included as a <nativelib> resource in the JNLP file.

getWindowID

public static long getWindowID(Window w)
Utility method to get the native window ID for a Java Window as a long value. This method is primarily for X11-based systems, which use an opaque XID (usually long int) to identify windows.

Throws: HeadlessException if the current VM is running headless

getWindowPointer

public static Pointer getWindowPointer(Window w)
Utility method to get the native window pointer for a Java Window as a Pointer value. This method is primarily for w32, which uses the HANDLE type (actually void *) to identify windows.

Throws: HeadlessException if the current VM is running headless

initialize_ffi_type

static int initialize_ffi_type(long type_info)
Returns the size (calculated by libffi) of the given type.

isProtected

public static boolean isProtected()
Returns whether protection is enabled. Check the result of this method after calling setProtected(true) to determine if this platform supports protecting memory accesses.

isSupportedNativeType

public static boolean isSupportedNativeType(Class cls)
Indicate whether the given class is supported as a native argument type.

loadLibrary

public static Object loadLibrary(Class interfaceClass)
Map a library interface to the current process, providing the explicit interface class.

Parameters: interfaceClass

loadLibrary

public static Object loadLibrary(Class interfaceClass, Map options)
Map a library interface to the current process, providing the explicit interface class.

Parameters: interfaceClass options Map of library options

loadLibrary

public static Object loadLibrary(String name, Class interfaceClass)
Map a library interface to the given shared library, providing the explicit interface class. If name is null, attempts to map onto the current process.

Parameters: name interfaceClass

loadLibrary

public static Object loadLibrary(String name, Class interfaceClass, Map options)
Load a library interface from the given shared library, providing the explicit interface class and a map of options for the library. If no library options are detected the map is interpreted as a map of Java method names to native function names.

If name is null, attempts to map onto the current process.

Parameters: name interfaceClass options Map of library options

main

public static void main(String[] args)
Prints JNA library details to the console.

register

public static void register(String libName)
When called from a class static initializer, maps all native methods found within that class to native libraries via the JNA raw calling interface.

Parameters: libName library name to which functions should be bound

register

public static void register(NativeLibrary lib)
When called from a class static initializer, maps all native methods found within that class to native libraries via the JNA raw calling interface.

Parameters: lib native library to which functions should be bound

register

public static void register(Class cls, NativeLibrary lib)
When called from a class static initializer, maps all native methods found within that class to native libraries via the JNA raw calling interface.

Parameters: lib library to which functions should be bound

setCallbackExceptionHandler

public static void setCallbackExceptionHandler(Callback.UncaughtExceptionHandler eh)
Set the default handler invoked when a callback throws an uncaught exception. If the given handler is null, the default handler will be reinstated.

setLastError

public static void setLastError(int code)
Set the OS last error code. Whether the setting is per-thread or global depends on the underlying OS.

setPreserveLastError

public static void setPreserveLastError(boolean enable)

Deprecated: The preferred method of obtaining the last error result is to declare your mapped method to throw LastErrorException instead.

Set whether the system last error result is captured after every native invocation. Defaults to true (false for direct-mapped calls).

setProtected

public static void setProtected(boolean enable)
Set whether native memory accesses are protected from invalid accesses. This should only be set true when testing or debugging, and should not be considered reliable or robust for applications where JNA native calls are occurring on multiple threads. Protected mode will be automatically set if the system property jna.protected has a value of "true" when the JNA library is first loaded.

If not supported by the underlying platform, this setting will have no effect.

NOTE: On platforms which support signals (non-Windows), JNA uses signals to trap errors. This may interfere with the JVM's own use of signals. When protected mode is enabled, you should make use of the jsig library, if available (see Signal Chaining). In short, set the environment variable LD_PRELOAD to the path to libjsig.so in your JRE lib directory (usually ${java.home}/lib/${os.arch}/libjsig.so) before launching your Java application.

synchronizedLibrary

public static Library synchronizedLibrary(Library library)
Returns a synchronized (thread-safe) library backed by the specified library. This wrapping will prevent simultaneous invocations of any functions mapped to a given NativeLibrary. Note that the native library may still be sensitive to being called from different threads.

Parameters: library the library to be "wrapped" in a synchronized library.

Returns: a synchronized view of the specified library.

toByteArray

public static byte[] toByteArray(String s)
Obtain a NUL-terminated byte buffer equivalent to the given String, using jna.encoding or the default platform encoding if that property is not set.

toByteArray

public static byte[] toByteArray(String s, String encoding)
Obtain a NUL-terminated byte buffer equivalent to the given String, using the given encoding.

toCharArray

public static char[] toCharArray(String s)
Obtain a NUL-terminated wide character buffer equivalent to the given String.

toString

public static String toString(byte[] buf)
Obtain a Java String from the given native byte array. If there is no NUL terminator, the String will comprise the entire array. If the system property jna.encoding is set, its value will override the platform default encoding (if supported).

toString

public static String toString(byte[] buf, String encoding)
Obtain a Java String from the given native byte array, using the given encoding. If there is no NUL terminator, the String will comprise the entire array. If the encoding parameter is null, the platform default encoding will be used.

toString

public static String toString(char[] buf)
Obtain a Java String from the given native wchar_t array. If there is no NUL terminator, the String will comprise the entire array.

unregister

public static void unregister()
Remove all native mappings for the calling class. Should only be called if the class is no longer referenced and about to be garbage collected.

unregister

public static void unregister(Class cls)
Remove all native mappings for the given class. Should only be called if the class is no longer referenced and about to be garbage collected.

updateLastError

static void updateLastError(int e)
Update the last error value (called from native code).
Copyright © 2007-2009 Timothy Wall. All Rights Reserved.