Top Description Inners Fields Constructors Methods
com.sun.jna

public final Class Native

extends Object
Class Inheritance
Imports
java.awt.Component, .GraphicsEnvironment, .HeadlessException, .Toolkit, .Window, java.io.File, .FileOutputStream, .IOException, .InputStream, .UnsupportedEncodingException, java.lang.ref.WeakReference, java.lang.reflect.Field, .InvocationHandler, .InvocationTargetException, .Method, .Modifier, .Proxy, java.net.URL, .URLDecoder, java.nio.Buffer, .ByteBuffer, java.util.Arrays, .Collections, .Map, .WeakHashMap, com.sun.jna.Structure.ByReference

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

getTypeMapper and getStructureAlignment 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.

Authors
Todd Fast, [email protected], [email protected]
See Also
Library

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
Native.W32Cleanup

For internal use only.

Field Summary

Modifier and TypeField and Description
private static Map<K, V>
private static final ThreadLocal<T>
private static Map<K, V>
public static final int
LONG_SIZE

Size of a native long type, in bytes.

private static Map<K, V>
public static final int
POINTER_SIZE

The size of a native pointer (void*) on the current platform, in bytes.

private static Map<K, V>
public static final int
WCHAR_SIZE

Size of a native wchar_t type, in bytes.

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
pack-priv static Class<T>
findLibraryClass(Class<T> cls)

Find the library interface corresponding to the given class.

private static native String
public static Pointer
getByteBufferPointer(ByteBuffer b)

Deprecated Use getDirectBufferPointer instead.
Convert a direct Buffer into a Pointer.
pack-priv static byte[]
getBytes(String s)

Return a byte array corresponding to the given String.

public static long
getComponentID(Component c)

Utility method to get the native window ID for a heavyweight Java Component as a long value.

public static Pointer
getComponentPointer(Component c)

Utility method to get the native window pointer for a heavyweight Java Component as a Pointer value.

public static native Pointer
getDirectBufferPointer(Buffer b)

Convert a direct Buffer into a Pointer.

public static int
getLastError()

Retrieve the last error set by the OS.

public static Map<K, V>
getLibraryOptions(Class<T> type)

Return the preferred native library configuration options for the given class.

private static String
public static int
getNativeSize(Class<T> cls)

Returns the native size for a given Java class.

private static native String
public static synchronized native boolean
getPreserveLastError()

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

public static int
getStructureAlignment(Class<T> cls)

Return the preferred structure alignment for the given native interface.

public static TypeMapper
getTypeMapper(Class<T> cls)

Return the preferred TypeMapper for the given native interface.

public static String
getWebStartLibraryPath(String libName)

If running web start, determine the location of a given native library.

private static native long
public static long
getWindowID(Window w)

Utility method to get the native window ID for a Java Window as a long value.

public static Pointer
getWindowPointer(Window w)

Utility method to get the native window pointer for a Java Window as a Pointer value.

private static native void
public static synchronized native boolean
isProtected()

Returns whether protection is enabled.

public static boolean
isSupportedNativeType(Class<T> cls)

Indicate whether the given class is supported as a native argument type.

private static boolean
loadInstance(Class<T> cls)

Attempts to force initialization of an instance of the library interface by loading a public static field of the requisite type.

public static Object
loadLibrary(String name, Class<T> interfaceClass)

Load a library interface from the given shared library, providing the explicit interface class.

public static Object
loadLibrary(String name, Class<T> interfaceClass, Map<K, V>
Map of library options
libOptions
)

Load a library interface from the given shared library, providing the explicit interface class and a map of options for the library.

private static void
private static native int
longSize()

Return the size of a native long.

public static void
main(String[] args)

Prints JNA library details to the console.

private static native int
pointerSize()

Initialize field and method IDs for native methods of this class.

public static native void
setLastError(int code)

Set the OS last error code.

public static synchronized native void
setPreserveLastError(boolean enable)

Set whether the system last error result is captured after every native invocation.

public static synchronized native void
setProtected(boolean enable)

Set whether native memory accesses are protected from invalid accesses.

public static Library

Returns:

a synchronized view of the specified library.
synchronizedLibrary
(final Library
the library to be "wrapped" in a synchronized library.
library
)

Returns a synchronized (thread-safe) library backed by the specified library.

public static String
toString(byte[] buf)

Obtain a Java String from the given native byte array.

public static String
toString(char[] buf)

Obtain a Java String from the given native wchar_t array.

pack-priv static void
updateLastError(int e)

Update the last error value (called from native code).

private static native int
wideCharSize()

Return the size of a native wchar_t.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

alignmentsback to summary
private static Map<K, V> alignments
lastErrorback to summary
private static final ThreadLocal<T> lastError
librariesback to summary
private static Map<K, V> libraries
LONG_SIZEback to summary
public static final int LONG_SIZE

Size of a native long type, in bytes.

optionsback to summary
private static Map<K, V> options
POINTER_SIZEback to summary
public static final int POINTER_SIZE

The size of a native pointer (void*) on the current platform, in bytes.

typeMappersback to summary
private static Map<K, V> typeMappers
WCHAR_SIZEback to summary
public static final int WCHAR_SIZE

Size of a native wchar_t type, in bytes.

Constructor Detail

Nativeback to summary
private Native()

Method Detail

findLibraryClassback to summary
pack-priv static Class<T> findLibraryClass(Class<T> cls)

Find the library interface corresponding to the given class. Checks all ancestor classes for a declaring class which implements Library.

getAPIChecksumback to summary
private static native String getAPIChecksum()
getByteBufferPointerback to summary
public static Pointer getByteBufferPointer(ByteBuffer b)

Deprecated

Use getDirectBufferPointer instead.

Convert a direct Buffer into a Pointer.

Exceptions
IllegalArgumentException:
if the buffer is not direct.
getBytesback to summary
pack-priv 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).

getComponentIDback to summary
public static long getComponentID(Component c) throws HeadlessException

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.

Exceptions
HeadlessException:
if the current VM is running headless
getComponentPointerback to summary
public static Pointer getComponentPointer(Component c) throws HeadlessException

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 HANDLE type (actually void *) to identify windows.

Exceptions
HeadlessException:
if the current VM is running headless
getDirectBufferPointerback to summary
public static native Pointer getDirectBufferPointer(Buffer b)

Convert a direct Buffer into a Pointer.

Exceptions
IllegalArgumentException:
if the buffer is not direct.
getLastErrorback to summary
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 getPreserveLastError is false.

getLibraryOptionsback to summary
public static Map<K, V> getLibraryOptions(Class<T> type)

Return the preferred native library configuration options for the given class.

See Also
Library
getNativeLibraryResourcePathback to summary
private static String getNativeLibraryResourcePath()
getNativeSizeback to summary
public static int getNativeSize(Class<T> cls)

Returns the native size for a given Java class. Structures are assumed to be struct pointers unless they implement Structure.ByValue.

getNativeVersionback to summary
private static native String getNativeVersion()
getPreserveLastErrorback to summary
public static synchronized native boolean getPreserveLastError()

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

getStructureAlignmentback to summary
public static int getStructureAlignment(Class<T> cls)

Return the preferred structure alignment for the given native interface.

See Also
Library#OPTION_STRUCTURE_ALIGNMENT
getTypeMapperback to summary
public static TypeMapper getTypeMapper(Class<T> cls)

Return the preferred TypeMapper for the given native interface.

See Also
Library#OPTION_TYPE_MAPPER
getWebStartLibraryPathback to summary
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.

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

Exceptions
IllegalArgumentException:
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.
getWindowHandle0back to summary
private static native long getWindowHandle0(Component c)
getWindowIDback to summary
public static long getWindowID(Window w) throws HeadlessException

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.

Exceptions
HeadlessException:
if the current VM is running headless
getWindowPointerback to summary
public static Pointer getWindowPointer(Window w) throws HeadlessException

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.

Exceptions
HeadlessException:
if the current VM is running headless
initIDsback to summary
private static native void initIDs()
isProtectedback to summary
public static synchronized native 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.

isSupportedNativeTypeback to summary
public static boolean isSupportedNativeType(Class<T> cls)

Indicate whether the given class is supported as a native argument type.

loadInstanceback to summary
private static boolean loadInstance(Class<T> cls)

Attempts to force initialization of an instance of the library interface by loading a public static field of the requisite type. Returns whether an instance variable was instantiated. Expects that lock on libraries is already held

loadLibraryback to summary
public static Object loadLibrary(String name, Class<T> interfaceClass)

Load a library interface from the given shared library, providing the explicit interface class.

loadLibraryback to summary
public static Object loadLibrary(String name, Class<T> interfaceClass, Map<K, V> libOptions)

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.

Parameters
libOptions:Map<K, V>

Map of library options

loadNativeLibraryback to summary
private static void loadNativeLibrary()
longSizeback to summary
private static native int longSize()

Return the size of a native long.

mainback to summary
public static void main(String[] args)

Prints JNA library details to the console.

pointerSizeback to summary
private static native int pointerSize()

Initialize field and method IDs for native methods of this class. Returns the size of a native pointer.

setLastErrorback to summary
public static native void setLastError(int code)

Set the OS last error code. Whether the setting is per-thread or global depends on the underlying OS.

setPreserveLastErrorback to summary
public static synchronized native void setPreserveLastError(boolean enable)

Set whether the system last error result is captured after every native invocation. Defaults to true.

setProtectedback to summary
public static synchronized native 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 multithreaded applications. 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.

synchronizedLibraryback to summary
public static Library synchronizedLibrary(final 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:Library

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

Returns:Library

a synchronized view of the specified library.

toStringback to summary
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).

toStringback to summary
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.

updateLastErrorback to summary
pack-priv static void updateLastError(int e)

Update the last error value (called from native code).

wideCharSizeback to summary
private static native int wideCharSize()

Return the size of a native wchar_t.

com.sun.jna back to summary

public Class Native.W32Cleanup

extends Thread
Class Inheritance

For internal use only.

Field Summary

Modifier and TypeField and Description
private File
Inherited from java.lang.Thread:
MAX_PRIORITYMIN_PRIORITYNORM_PRIORITY

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public static void
main(String[] args)

public void
run()

Overrides java.lang.Thread.run.

Implements java.lang.Runnable.run.

This method is run by the thread when it executes.
Inherited from java.lang.Thread:
activeCountcheckAccessclonecountStackFramescurrentThreaddumpStackenumerategetAllStackTracesgetContextClassLoadergetDefaultUncaughtExceptionHandlergetIdgetNamegetPrioritygetStackTracegetStategetThreadGroupgetUncaughtExceptionHandlerholdsLockinterruptinterruptedisAliveisDaemonisInterruptedisVirtualjoinjoinjoinjoinofPlatformofVirtualonSpinWaitresumesetContextClassLoadersetDaemonsetDefaultUncaughtExceptionHandlersetNamesetPrioritysetUncaughtExceptionHandlersleepsleepsleepstartstartVirtualThreadstopsuspendthreadIdtoStringyield

Field Detail

fileback to summary
private File file

Constructor Detail

W32Cleanupback to summary
public W32Cleanup(File file)

Method Detail

mainback to summary
public static void main(String[] args)
runback to summary
public void run()

Overrides java.lang.Thread.run.

Implements java.lang.Runnable.run.

Doc from java.lang.Thread.run.

This method is run by the thread when it executes. Subclasses of Thread may override this method.

This method is not intended to be invoked directly. If this thread is a platform thread created with a Runnable task then invoking this method will invoke the task's run method. If this thread is a virtual thread then invoking this method directly does nothing.