If running web start, determine the location of a given native
library.
Call the native function being represented by this object, returning
a Java
Object
.
Call the native function being represented by this object, returning
a struct by value.
Indicate whether the given class is supported as a native argument
type.
Map a library interface to the current process, providing
the explicit interface class.
Map a library interface to the current process, providing
the explicit interface class.
Map a library interface to the given shared library, providing
the explicit interface class.
Load a library interface from the given shared library, providing
the explicit interface class and a map of options for the library.
Open the requested native library with the specified platform-specific
otions.
When called from a class static initializer, maps all native methods
found within that class to native libraries via the JNA raw calling
interface.
When called from a class static initializer, maps all native methods
found within that class to native libraries via the JNA raw calling
interface.
When called from a class static initializer, maps all native methods
found within that class to native libraries via the JNA raw calling
interface.
When called from a class static initializer, maps all native methods
found within that class to native libraries via the JNA raw calling
interface.
Set the default handler invoked when a callback throws an uncaught
exception.
Deprecated.
static void
setProtected
(boolean enable)
Set whether native memory accesses are protected from invalid
accesses.
(package private) static void
setShort
(long addr,
short value)
(package private) static void
setWideString
(long addr,
String
value)
static
Library
synchronizedLibrary
(
Library
library)
Returns a synchronized (thread-safe) library backed by the specified
library.
static byte[]
toByteArray
(
String
s)
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
String
toString
(byte[] buf)
Obtain a Java String from the given native byte array.
static
String
toString
(byte[] buf,
String
encoding)
Obtain a Java String from the given native byte array, using the given
encoding.
static
String
toString
(char[] buf)
Obtain a Java String from the given native wchar_t array.
static
List
<
String
>
toStringList
(char[] buf)
Converts a "list" of strings each null terminated
into a
List
of
String
values.
static
List
<
String
>
toStringList
(char[] buf,
int offset,
int len)
Converts a "list" of strings each null terminated
into a
List
of
String
values.
static void
unregister
()
Remove all native mappings for the calling class.
static void
unregister
(
Class
cls)
Remove all native mappings for the given class.
(package private) static void
write
(long addr,
byte[] buf,
int index,
int length)
(package private) static void
write
(long addr,
char[] buf,
int index,
int length)
(package private) static void
write
(long addr,
double[] buf,
int index,
int length)
(package private) static void
write
(long addr,
float[] buf,
int index,
int length)
(package private) static void
write
(long addr,
int[] buf,
int index,
int length)
(package private) static void
write
(long addr,
long[] buf,
int index,
int length)
(package private) static void
write
(long addr,
short[] buf,
int index,
int length)
POINTER_SIZE
public static final int POINTER_SIZE
The size of a native pointer (
void*
) on the current
platform, in bytes.
CB_HAS_INITIALIZER
static final int CB_HAS_INITIALIZER
Indicates whether the callback has an initializer.
See Also:
Constant Field Values
deleteLibrary
static boolean deleteLibrary(File lib)
Remove any automatically unpacked native library.
This will fail on windows, which disallows removal of any file that is
still in use, so an alternative is required in that case. Mark
the file that could not be deleted, and attempt to delete any
temporaries on next startup.
Do NOT force the class loader to unload the native library, since
that introduces issues with cleaning up any extant JNA bits
(e.g. Memory) which may still need use of the library before shutdown.
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.
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.
@Deprecated
public static void setPreserveLastError(boolean enable)
Deprecated.
This method is obsolete. The last error value is always preserved.
See Also:
getLastError()
@Deprecated
public static boolean getPreserveLastError()
Deprecated.
Indicates whether the system last error result is preserved
after every invocation. Always returns
true
See Also:
getLastError()
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.
Throws:
HeadlessException
- if the current VM is running headless
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.
Throws:
HeadlessException
- if the current VM is running headless
getWindowPointer
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.
Throws:
HeadlessException
- if the current VM is running headless
getComponentPointer
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
HWND
type (actually
void *
) to identify windows.
Throws:
HeadlessException
- if the current VM is running headless
getDirectBufferPointer
public static Pointer getDirectBufferPointer(Buffer b)
Throws:
IllegalArgumentException
- if the buffer is not direct.
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. The
encoding is obtained from
getDefaultStringEncoding()
.
Parameters:
buf
- The buffer containing the encoded bytes
See Also:
toString(byte[], String)
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.
Parameters:
buf
- The buffer containing the encoded bytes
encoding
- The encoding name - if
null
then 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.
Parameters:
buf
- The buffer containing the characters
toStringList
public static List<String> toStringList(char[] buf)
Converts a "list" of strings each null terminated
into a
List
of
String
values. The end of the
list is signaled by an extra NULL value at the end or by the
end of the buffer.
Parameters:
buf
- The buffer containing the strings
Returns:
A
List
of all the strings in the buffer
See Also:
toStringList(char[], int, int)
int len)
Converts a "list" of strings each null terminated
into a
List
of
String
values. The end of the
list is signaled by an extra NULL value at the end or by the
end of the data.
Parameters:
buf
- The buffer containing the strings
offset
- Offset to start parsing
len
- The total characters to parse
Returns:
A
List
of all the strings in the buffer
loadLibrary
public static Object loadLibrary(Class interfaceClass)
Map a library interface to the current process, providing
the explicit interface class.
Native libraries loaded via this method may be found in
several locations
.
Parameters:
interfaceClass
-
Returns:
an instance of the requested interface, mapped to the current
process.
Throws:
UnsatisfiedLinkError
- if the library cannot be found or
dependent libraries are missing.
public static Object loadLibrary(Class interfaceClass,
Map options)
Map a library interface to the current process, providing
the explicit interface class. Any options provided for the library are
cached and associated with the library and any of its defined
structures and/or functions.
Native libraries loaded via this method may be found in
several locations
.
Parameters:
interfaceClass
-
options
- Map of library options
Returns:
an instance of the requested interface, mapped to the current
process.
Throws:
UnsatisfiedLinkError
- if the library cannot be found or
dependent libraries are missing.
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.
Native libraries loaded via this method may be found in
several locations
.
Parameters:
name
-
interfaceClass
-
Returns:
an instance of the requested interface, mapped to the indicated
native library.
Throws:
UnsatisfiedLinkError
- if the library cannot be found or
dependent libraries are missing.
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.
Native libraries loaded via this method may be found in
several locations
.
Parameters:
name
-
interfaceClass
-
options
- Map of library options
Returns:
an instance of the requested interface, mapped to the indicated
native library.
Throws:
UnsatisfiedLinkError
- if the library cannot be found or
dependent libraries are missing.
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
.
getLibraryOptions
public static Map getLibraryOptions(Class type)
Return the preferred native library configuration options for the given
class. First attempts to load any field of the interface type within
the interface mapping, then checks the cache for any specified library
options. If none found, a set of library options will be generated
from the fields (by order of precedence)
OPTIONS
(a
Map
),
TYPE_MAPPER
(a
TypeMapper
),
STRUCTURE_ALIGNMENT
(an
Integer
), and
STRING_ENCODING
(a
String
).
See Also:
Library
getTypeMapper
public static TypeMapper getTypeMapper(Class cls)
getStringEncoding
public static String getStringEncoding(Class cls)
getDefaultStringEncoding
public static String getDefaultStringEncoding()
Return the default string encoding. Returns the value of the system
property
jna.encoding
or
DEFAULT_ENCODING
.
getStructureAlignment
public static int getStructureAlignment(Class cls)
getBytes
static byte[] getBytes(String s)
static byte[] getBytes(String s,
String encoding)
Return a byte array corresponding to the given String, using the given
encoding. If the encoding is not found default to the platform native
encoding.
toByteArray
public static byte[] toByteArray(String s)
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.
extractFromResourcePath
public static File extractFromResourcePath(String name)
throws IOException
Attempt to extract a native library from the current resource path,
using the current thread context class loader.
Parameters:
name
- Base name of native library to extract. May also be an
absolute resource path (i.e. starts with "/"), in which case the
no transformations of the library name are performed. If only the base
name is given, the resource path is attempted both with and without
Platform.RESOURCE_PREFIX
, after mapping the library name via
NativeLibrary.mapSharedLibraryName(String)
.
Returns:
File indicating extracted resource on disk
Throws:
IOException
- if resource not found
extractFromResourcePath
public static File extractFromResourcePath(String name,
ClassLoader loader)
throws IOException
Attempt to extract a native library from the resource path using the
given class loader.
Parameters:
name
- Base name of native library to extract. May also be an
absolute resource path (i.e. starts with "/"), in which case the
no transformations of the library name are performed. If only the base
name is given, the resource path is attempted both with and without
Platform.RESOURCE_PREFIX
, after mapping the library name via
NativeLibrary.mapSharedLibraryName(String)
.
loader
- Class loader to use to load resources
Returns:
File indicating extracted resource on disk
Throws:
IOException
- if resource not found
getLastError
public static int getLastError()
Retrieve 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.
An alternative method of obtaining the last error result is
to declare your mapped method to throw
LastErrorException
instead. If a method's signature includes a throw of
LastErrorException
, the last error will be set to zero before the
native call and a
LastErrorException
will be raised if the last
error value is non-zero after the call, regardless of the actual
returned value from the native function.
setLastError
public static void setLastError(int code)
Set the OS last error code. The value will be saved on a per-thread
basis.
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.
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.
static File getTempDir()
throws IOException
Obtain a directory suitable for writing JNA-specific temporary files.
Override with
jna.tmpdir
Throws:
IOException
static void removeTemporaryFiles()
throws IOException
Remove all marked temporary files in the given directory.
Throws:
IOException
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
Structure.ByValue
.
isSupportedNativeType
public static boolean isSupportedNativeType(Class cls)
Indicate whether the given class is supported as a native argument
type.
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.
getCallbackExceptionHandler
public static Callback.UncaughtExceptionHandler getCallbackExceptionHandler()
Returns the current handler for callback uncaught exceptions.
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
getCallingClass
static Class getCallingClass()
setCallbackThreadInitializer
public static void setCallbackThreadInitializer(Callback cb,
CallbackThreadInitializer initializer)
Set a thread initializer for the given callback.
The thread initializer indicates desired thread configuration when the
given Callback is invoked on a native thread not yet attached to the
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.
public static void register(Class cls,
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. Uses the class loader of the given class to search for the
native library in the resource path if it is not found in the system
library load path or
jna.library.path
.
Parameters:
cls
- Class with native methods to register
libName
- name of or path to native library to which functions
should be bound
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:
cls
- Class with native methods to register
lib
- library to which functions should be bound
static long createNativeCallback(Callback callback,
Method method,
Class[] parameterTypes,
Class returnType,
int callingConvention,
int flags,
String encoding)
Create a native trampoline to delegate execution to the Java callback.
fp
- function pointer
callFlags
- calling convention to be used
args
- Arguments to pass to the native function
Returns:
The value returned by the target native function
fp
- function pointer
callFlags
- calling convention to be used
args
- Arguments to pass to the native function
Returns:
The value returned by the target native function
fp
- function pointer
callFlags
- calling convention to be used
args
- Arguments to pass to the native function
Returns:
The value returned by the target native function
fp
- function pointer
callFlags
- calling convention to be used
args
- Arguments to pass to the native function
Returns:
The value returned by the target native function
fp
- function pointer
callFlags
- calling convention to be used
args
- Arguments to pass to the native function
Returns:
The native pointer returned by the target native function
Object
[] args,
Structure
s)
Call the native function being represented by this object, returning
a struct by value.
Parameters:
fp
- function pointer
callFlags
- calling convention to be used
args
- Arguments to pass to the native function
Returns:
the passed-in Structure
int callFlags,
Object
[] args)
Call the native function being represented by this object, returning
a Java
Object
.
Parameters:
fp
- function pointer
callFlags
- calling convention to be used
args
- Arguments to pass to the native function
Returns:
The returned Java
Object
static long open(String name,
int flags)
Open the requested native library with the specified platform-specific
otions.
size
- size of the memory to be allocated
Returns:
native address of the allocated memory block; zero if the
allocation failed.
public static ByteBuffer getDirectByteBuffer(long addr,
long length)
Get a direct ByteBuffer mapped to the memory pointed to by the pointer.
This method calls through to the JNA NewDirectByteBuffer method.
Parameters:
addr
- base address of the JNA-originated memory
length
- Length of ByteBuffer
Returns:
a direct ByteBuffer that accesses the memory being pointed to,
detach
public static void detach(boolean detach)
Indicate whether the JVM should detach the current native thread when
the current Java code finishes execution. Generally this is used to
avoid detaching native threads when it is known that a given thread
will be relatively long-lived and call back to Java code frequently.
This call is lightweight; it only results in an additional JNI
crossing if the desired state changes from its last setting.
Throws:
IllegalStateException
- if
detach(true)
is
called on a thread created by the JVM.