Class Native
- java.lang.Object
-
- com.sun.jna.Native
-
- All Implemented Interfaces:
Version
public final class Native extends java.lang.Object implements Version
Provides generation of invocation plumbing for a defined native library interface. Also provides various utilities for native operations.getTypeMapper(java.lang.Class<?>)andgetStructureAlignment(java.lang.Class<?>)are provided to avoid having to explicitly pass these parameters toStructures, which would require everyStructurewhich requires custom mapping or alignment to define a constructor and pass parameters to the superclass. To avoid lots of boilerplate, the baseStructureconstructor 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 any paths defined in
jna.boot.library.path(if defined), then the system library path usingSystem.loadLibrary(java.lang.String), unlessjna.nosys=true. If not found, the appropriate library will be extracted from the class path (into a temporary directory if found within a jar file) and loaded from there, unlessjna.noclasspath=true. 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.To avoid the automatic unpacking (in situations where you want to force a failure if the JNA native library is not properly installed on the system), set the system property
jna.nounpack=true.While this class and its corresponding native library are loaded, the system property
jna.loadedwill be set. The property will be cleared when native support has been unloaded (i.e. the Native class and its underlying native support has been GC'd).NOTE: all native functions are provided within this class to ensure that all other JNA-provided classes and objects are GC'd and/or finalized/disposed before this class is disposed and/or removed from memory (most notably Memory and any other class which by default frees its resources in a finalizer).
Native Library Loading
Native libraries loaded viaload(Class)may be found in several locations.- Author:
- Todd Fast, todd.fast@sun.com, twall@users.sf.net
- See Also:
Library
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceNative.ffi_callback
-
Field Summary
Fields Modifier and Type Field Description static intBOOL_SIZESize of a nativebooltype (C99 and later), in bytes.(package private) static intCB_HAS_INITIALIZERIndicates whether the callback has an initializer.(package private) static intCB_OPTION_DIRECTUse direct mapping for callback.(package private) static intCB_OPTION_IN_DLLReturn a DLL-resident fucntion pointer.static booleanDEBUG_JNA_LOADstatic booleanDEBUG_LOADstatic java.nio.charset.CharsetDEFAULT_CHARSETstatic java.lang.StringDEFAULT_ENCODING(package private) static java.lang.StringJNA_TMPLIB_PREFIX(package private) static java.lang.StringjnidispatchPathstatic intLONG_DOUBLE_SIZESize of a nativelong doubletype (C99 and later), in bytes.static intLONG_SIZESize of a nativelongtype, in bytes.(package private) static intMAX_ALIGNMENT(package private) static intMAX_PADDINGstatic intPOINTER_SIZEThe size of a native pointer (void*) on the current platform, in bytes.static intSIZE_T_SIZESize of a nativesize_ttype, in bytes.static intWCHAR_SIZESize of a nativewchar_ttype, in bytes.-
Fields inherited from interface com.sun.jna.Version
VERSION, VERSION_NATIVE
-
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description (package private) static voidclose(long handle)Close the given native library.(package private) static longcreateNativeCallback(Callback callback, java.lang.reflect.Method method, java.lang.Class<?>[] parameterTypes, java.lang.Class<?> returnType, int callingConvention, int flags, java.lang.String encoding)Create a native trampoline to delegate execution to the Java callback.(package private) static booleandeleteLibrary(java.io.File lib)Remove any automatically unpacked native library.static voiddetach(boolean detach)Indicate whether the JVM should detach the current native thread when the current Java code finishes execution.static java.io.FileextractFromResourcePath(java.lang.String name)Attempt to extract a native library from the current resource path, using the current thread context class loader.static java.io.FileextractFromResourcePath(java.lang.String name, java.lang.ClassLoader loader)Attempt to extract a native library from the resource path using the given class loader.static voidffi_call(long cif, long fptr, long resp, long args)Make an FFI function call.static voidffi_free_closure(long closure)static longffi_prep_cif(int abi, int nargs, long ffi_return_type, long ffi_types)Create a new cif structure.static longffi_prep_closure(long cif, Native.ffi_callback cb)(package private) static java.lang.Class<?>findDirectMappedClass(java.lang.Class<?> cls)Find the nearest enclosing class with native methods.(package private) static java.lang.Class<?>findEnclosingLibraryClass(java.lang.Class<?> cls)Find the library interface corresponding to the given class.(package private) static longfindSymbol(long handle, java.lang.String name)static voidfree(long ptr)Call the real native free(package private) static voidfreeNativeCallback(long ptr)Free the given callback trampoline.(package private) static bytegetByte(Pointer pointer, long baseaddr, long offset)(package private) static byte[]getBytes(java.lang.String s)(package private) static byte[]getBytes(java.lang.String s, java.lang.String encoding)(package private) static byte[]getBytes(java.lang.String s, java.nio.charset.Charset charset)static Callback.UncaughtExceptionHandlergetCallbackExceptionHandler()(package private) static java.lang.Class<?>getCallingClass()Try to determine the class context in which aregister(String)call was made.(package private) static chargetChar(Pointer pointer, long baseaddr, long offset)static longgetComponentID(java.awt.Component c)Utility method to get the native window ID for a heavyweight JavaComponentas alongvalue.static PointergetComponentPointer(java.awt.Component c)Utility method to get the native window pointer for a heavyweight JavaComponentas aPointervalue.static java.lang.StringgetDefaultStringEncoding()static PointergetDirectBufferPointer(java.nio.Buffer b)Convert a directBufferinto aPointer.(package private) static java.nio.ByteBuffergetDirectByteBuffer(Pointer pointer, long addr, long offset, long length)(package private) static doublegetDouble(Pointer pointer, long baseaddr, long offset)(package private) static floatgetFloat(Pointer pointer, long baseaddr, long offset)(package private) static intgetInt(Pointer pointer, long baseaddr, long offset)static intgetLastError()Retrieve last error set by the OS.static java.util.Map<java.lang.String,java.lang.Object>getLibraryOptions(java.lang.Class<?> type)Return the preferred native library configuration options for the given class.(package private) static longgetLong(Pointer pointer, long baseaddr, long offset)static intgetNativeSize(java.lang.Class<?> cls)Returns the native size for a given Java class.static intgetNativeSize(java.lang.Class<?> type, java.lang.Object value)(package private) static PointergetPointer(long addr)(package private) static shortgetShort(Pointer pointer, long baseaddr, long offset)(package private) static java.lang.StringgetSignature(java.lang.Class<?> cls)(package private) static java.lang.StringgetString(Pointer pointer, long offset)(package private) static java.lang.StringgetString(Pointer pointer, long offset, java.lang.String encoding)(package private) static byte[]getStringBytes(Pointer pointer, long baseaddr, long offset)static java.lang.StringgetStringEncoding(java.lang.Class<?> cls)static intgetStructureAlignment(java.lang.Class<?> cls)(package private) static java.io.FilegetTempDir()Obtain a directory suitable for writing JNA-specific temporary files.(package private) static PointergetTerminationFlag(java.lang.Thread t)static TypeMappergetTypeMapper(java.lang.Class<?> cls)Return the preferredTypeMapperfor the given native interface.static java.lang.StringgetWebStartLibraryPath(java.lang.String libName)If running web start, determine the location of a given native library.(package private) static java.lang.StringgetWideString(Pointer pointer, long baseaddr, long offset)(package private) static longgetWindowHandle0(java.awt.Component c)static longgetWindowID(java.awt.Window w)Utility method to get the native window ID for a JavaWindowas alongvalue.static PointergetWindowPointer(java.awt.Window w)Utility method to get the native window pointer for a JavaWindowas aPointervalue.(package private) static longindexOf(Pointer pointer, long baseaddr, long offset, byte value)(package private) static intinitialize_ffi_type(long type_info)Returns the size (calculated by libffi) of the given type.(package private) static doubleinvokeDouble(Function function, long fp, int callFlags, java.lang.Object[] args)Call the native function.(package private) static floatinvokeFloat(Function function, long fp, int callFlags, java.lang.Object[] args)Call the native function.(package private) static intinvokeInt(Function function, long fp, int callFlags, java.lang.Object[] args)Call the native function.(package private) static longinvokeLong(Function function, long fp, int callFlags, java.lang.Object[] args)Call the native function.(package private) static java.lang.ObjectinvokeObject(Function function, long fp, int callFlags, java.lang.Object[] args)Call the native function, returning a JavaObject.(package private) static longinvokePointer(Function function, long fp, int callFlags, java.lang.Object[] args)Call the native function.(package private) static StructureinvokeStructure(Function function, long fp, int callFlags, java.lang.Object[] args, Structure s)Call the native function, returning a struct by value.(package private) static voidinvokeVoid(Function function, long fp, int callFlags, java.lang.Object[] args)Call the native function.(package private) static booleanisCompatibleVersion(java.lang.String expectedVersion, java.lang.String nativeVersion)Version string must have the structure. . a bugfix change in the native code increments revision, the minor is incremented for backwards compatible changes and the major version is changed for backwards incompatbile changes. static booleanisProtected()Returns whether protection is enabled.static booleanisSupportedNativeType(java.lang.Class<?> cls)(package private) static booleanisUnpacked(java.io.File file)Identify temporary files unpacked from classpath jar files.static <T extends Library>
Tload(java.lang.Class<T> interfaceClass)Map a library interface to the current process, providing the explicit interface class.static <T extends Library>
Tload(java.lang.Class<T> interfaceClass, java.util.Map<java.lang.String,?> options)Map a library interface to the current process, providing the explicit interface class.static <T extends Library>
Tload(java.lang.String name, java.lang.Class<T> interfaceClass)Map a library interface to the given shared library, providing the explicit interface class.static <T extends Library>
Tload(java.lang.String name, java.lang.Class<T> interfaceClass, java.util.Map<java.lang.String,?> options)Load a library interface from the given shared library, providing the explicit interface class and a map of options for the library.static <T> TloadLibrary(java.lang.Class<T> interfaceClass)Deprecated.static <T> TloadLibrary(java.lang.Class<T> interfaceClass, java.util.Map<java.lang.String,?> options)Deprecated.static <T> TloadLibrary(java.lang.String name, java.lang.Class<T> interfaceClass)Deprecated.static <T> TloadLibrary(java.lang.String name, java.lang.Class<T> interfaceClass, java.util.Map<java.lang.String,?> options)Deprecated.static voidmain(java.lang.String[] args)Prints JNA library details to the console.static longmalloc(long size)Call the real native malloc(package private) static voidmarkTemporaryFile(java.io.File file)Perform cleanup of automatically unpacked native shared library.(package private) static longopen(java.lang.String name)Open the requested native library with default options.(package private) static longopen(java.lang.String name, int flags)Open the requested native library with the specified platform-specific otions.(package private) static voidread(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length)(package private) static voidread(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length)(package private) static voidread(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length)(package private) static voidread(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length)(package private) static voidread(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length)(package private) static voidread(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length)(package private) static voidread(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length)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(java.lang.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 voidregister(java.lang.Class<?> cls, java.lang.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(java.lang.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 booleanregistered(java.lang.Class<?> cls)(package private) static voidremoveTemporaryFiles()Remove all marked temporary files in the given directory.(package private) static java.lang.Stringreplace(java.lang.String s1, java.lang.String s2, java.lang.String str)(package private) static voidsetByte(Pointer pointer, long baseaddr, long offset, byte value)static voidsetCallbackExceptionHandler(Callback.UncaughtExceptionHandler eh)Set the default handler invoked when a callback throws an uncaught exception.static voidsetCallbackThreadInitializer(Callback cb, CallbackThreadInitializer initializer)Set a thread initializer for the given callback.(package private) static voidsetChar(Pointer pointer, long baseaddr, long offset, char value)(package private) static voidsetDouble(Pointer pointer, long baseaddr, long offset, double value)(package private) static voidsetFloat(Pointer pointer, long baseaddr, long offset, float value)(package private) static voidsetInt(Pointer pointer, long baseaddr, long offset, int value)static voidsetLastError(int code)Set the OS last error code.(package private) static voidsetLong(Pointer pointer, long baseaddr, long offset, long value)(package private) static voidsetMemory(Pointer pointer, long baseaddr, long offset, long length, byte value)(package private) static voidsetPointer(Pointer pointer, long baseaddr, long offset, long value)static voidsetProtected(boolean enable)Set whether native memory accesses are protected from invalid accesses.(package private) static voidsetShort(Pointer pointer, long baseaddr, long offset, short value)(package private) static voidsetWideString(Pointer pointer, long baseaddr, long offset, java.lang.String value)static LibrarysynchronizedLibrary(Library library)Returns a synchronized (thread-safe) library backed by the specified library.static byte[]toByteArray(java.lang.String s)static byte[]toByteArray(java.lang.String s, java.lang.String encoding)static byte[]toByteArray(java.lang.String s, java.nio.charset.Charset charset)static char[]toCharArray(java.lang.String s)static java.lang.StringtoString(byte[] buf)Obtain a Java String from the given native byte array.static java.lang.StringtoString(byte[] buf, java.lang.String encoding)Obtain a Java String from the given native byte array, using the given encoding.static java.lang.StringtoString(byte[] buf, java.nio.charset.Charset charset)Obtain a Java String from the given native byte array, using the given encoding.static java.lang.StringtoString(char[] buf)Obtain a Java String from the given native wchar_t array.static java.util.List<java.lang.String>toStringList(char[] buf)Converts a "list" of strings each null terminated into aListofStringvalues.static java.util.List<java.lang.String>toStringList(char[] buf, int offset, int len)Converts a "list" of strings each null terminated into aListofStringvalues.static voidunregister()Remove all native mappings for the calling class.static voidunregister(java.lang.Class<?> cls)Remove all native mappings for the given class.(package private) static voidwrite(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length)(package private) static voidwrite(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length)(package private) static voidwrite(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length)(package private) static voidwrite(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length)(package private) static voidwrite(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length)(package private) static voidwrite(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length)(package private) static voidwrite(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length)
-
-
-
Field Detail
-
DEFAULT_CHARSET
public static final java.nio.charset.Charset DEFAULT_CHARSET
-
DEFAULT_ENCODING
public static final java.lang.String DEFAULT_ENCODING
-
DEBUG_LOAD
public static final boolean DEBUG_LOAD
-
DEBUG_JNA_LOAD
public static final boolean DEBUG_JNA_LOAD
-
jnidispatchPath
static java.lang.String jnidispatchPath
-
POINTER_SIZE
public static final int POINTER_SIZE
The size of a native pointer (void*) on the current platform, in bytes.
-
LONG_SIZE
public static final int LONG_SIZE
Size of a nativelongtype, in bytes.
-
WCHAR_SIZE
public static final int WCHAR_SIZE
Size of a nativewchar_ttype, in bytes.
-
SIZE_T_SIZE
public static final int SIZE_T_SIZE
Size of a nativesize_ttype, in bytes.
-
BOOL_SIZE
public static final int BOOL_SIZE
Size of a nativebooltype (C99 and later), in bytes.
-
LONG_DOUBLE_SIZE
public static final int LONG_DOUBLE_SIZE
Size of a nativelong doubletype (C99 and later), in bytes.
-
MAX_ALIGNMENT
static final int MAX_ALIGNMENT
-
MAX_PADDING
static final int MAX_PADDING
-
JNA_TMPLIB_PREFIX
static final java.lang.String JNA_TMPLIB_PREFIX
- See Also:
- Constant Field Values
-
CB_HAS_INITIALIZER
static final int CB_HAS_INITIALIZER
Indicates whether the callback has an initializer.- See Also:
- Constant Field Values
-
CB_OPTION_DIRECT
static final int CB_OPTION_DIRECT
Use direct mapping for callback.- See Also:
- Constant Field Values
-
CB_OPTION_IN_DLL
static final int CB_OPTION_IN_DLL
Return a DLL-resident fucntion pointer.- See Also:
- Constant Field Values
-
-
Method Detail
-
isCompatibleVersion
static boolean isCompatibleVersion(java.lang.String expectedVersion, java.lang.String nativeVersion)Version string must have the structure. . a bugfix change in the native code increments revision, the minor is incremented for backwards compatible changes and the major version is changed for backwards incompatbile changes. - Parameters:
expectedVersion-nativeVersion-- Returns:
- true if nativeVersion describes a version compatible to expectedVersion
-
deleteLibrary
static boolean deleteLibrary(java.io.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 propertyjna.protectedhas 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_PRELOADto the path tolibjsig.soin 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 callingsetProtected(true)to determine if this platform supports protecting memory accesses.
-
getWindowID
public static long getWindowID(java.awt.Window w) throws java.awt.HeadlessExceptionUtility method to get the native window ID for a JavaWindowas alongvalue. This method is primarily for X11-based systems, which use an opaqueXID(usuallylong int) to identify windows.- Throws:
java.awt.HeadlessException- if the current VM is running headless
-
getComponentID
public static long getComponentID(java.awt.Component c) throws java.awt.HeadlessExceptionUtility method to get the native window ID for a heavyweight JavaComponentas alongvalue. This method is primarily for X11-based systems, which use an opaqueXID(usuallylong int) to identify windows.- Throws:
java.awt.HeadlessException- if the current VM is running headless
-
getWindowPointer
public static Pointer getWindowPointer(java.awt.Window w) throws java.awt.HeadlessException
Utility method to get the native window pointer for a JavaWindowas aPointervalue. This method is primarily for w32, which uses theHANDLEtype (actuallyvoid *) to identify windows.- Throws:
java.awt.HeadlessException- if the current VM is running headless
-
getComponentPointer
public static Pointer getComponentPointer(java.awt.Component c) throws java.awt.HeadlessException
Utility method to get the native window pointer for a heavyweight JavaComponentas aPointervalue. This method is primarily for w32, which uses theHWNDtype (actuallyvoid *) to identify windows.- Throws:
java.awt.HeadlessException- if the current VM is running headless
-
getWindowHandle0
static long getWindowHandle0(java.awt.Component c)
-
getDirectBufferPointer
public static Pointer getDirectBufferPointer(java.nio.Buffer b)
Convert a directBufferinto aPointer.- Throws:
java.lang.IllegalArgumentException- if the buffer is not direct.
-
toString
public static java.lang.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 fromgetDefaultStringEncoding().- Parameters:
buf- The buffer containing the encoded bytes- See Also:
toString(byte[], String)
-
toString
public static java.lang.String toString(byte[] buf, java.lang.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.Usage note: This function assumes, that
bufholds achararray. This means only single-byte encodings are supported.- Parameters:
buf- The buffer containing the encoded bytes. Must not benull.encoding- The encoding name - ifnullthen the platform default encoding will be used
-
toString
public static java.lang.String toString(byte[] buf, java.nio.charset.Charset charset)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.Usage note: This function assumes, that
bufholds achararray. This means only single-byte encodings are supported.- Parameters:
buf- The buffer containing the encoded bytes. Must not benull.charset- The charset to decodebuf. Must not benull.
-
toString
public static java.lang.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 java.util.List<java.lang.String> toStringList(char[] buf)
Converts a "list" of strings each null terminated into aListofStringvalues. 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
Listof all the strings in the buffer - See Also:
toStringList(char[], int, int)
-
toStringList
public static java.util.List<java.lang.String> toStringList(char[] buf, int offset, int len)Converts a "list" of strings each null terminated into aListofStringvalues. 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 stringsoffset- Offset to start parsinglen- The total characters to parse- Returns:
- A
Listof all the strings in the buffer
-
load
public static <T extends Library> T load(java.lang.Class<T> 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.- Type Parameters:
T- Type of expected wrapper- Parameters:
interfaceClass- The implementation wrapper interface- Returns:
- an instance of the requested interface, mapped to the current process.
- Throws:
java.lang.UnsatisfiedLinkError- if the library cannot be found or dependent libraries are missing.
-
load
public static <T extends Library> T load(java.lang.Class<T> interfaceClass, java.util.Map<java.lang.String,?> 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.- Type Parameters:
T- Type of expected wrapper- Parameters:
interfaceClass- The implementation wrapper interfaceoptions- Map of library options- Returns:
- an instance of the requested interface, mapped to the current process.
- Throws:
java.lang.UnsatisfiedLinkError- if the library cannot be found or dependent libraries are missing.- See Also:
load(String, Class, Map)
-
load
public static <T extends Library> T load(java.lang.String name, java.lang.Class<T> interfaceClass)
Map a library interface to the given shared library, providing the explicit interface class. Ifnameis null, attempts to map onto the current process. Native libraries loaded via this method may be found in several locations.- Type Parameters:
T- Type of expected wrapper- Parameters:
name- Library base nameinterfaceClass- The implementation wrapper interface- Returns:
- an instance of the requested interface, mapped to the indicated native library.
- Throws:
java.lang.UnsatisfiedLinkError- if the library cannot be found or dependent libraries are missing.- See Also:
load(String, Class, Map)
-
load
public static <T extends Library> T load(java.lang.String name, java.lang.Class<T> interfaceClass, java.util.Map<java.lang.String,?> 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
nameis null, attempts to map onto the current process. Native libraries loaded via this method may be found in several locations.- Type Parameters:
T- Type of expected wrapper- Parameters:
name- Library base nameinterfaceClass- The implementation wrapper interfaceoptions- Map of library options- Returns:
- an instance of the requested interface, mapped to the indicated native library.
- Throws:
java.lang.UnsatisfiedLinkError- if the library cannot be found or dependent libraries are missing.
-
loadLibrary
@Deprecated public static <T> T loadLibrary(java.lang.Class<T> interfaceClass)
Deprecated.Provided for improved compatibility between JNA 4.X and 5.X- See Also:
load(java.lang.Class)
-
loadLibrary
@Deprecated public static <T> T loadLibrary(java.lang.Class<T> interfaceClass, java.util.Map<java.lang.String,?> options)Deprecated.Provided for improved compatibility between JNA 4.X and 5.X- See Also:
load(java.lang.Class, java.util.Map)
-
loadLibrary
@Deprecated public static <T> T loadLibrary(java.lang.String name, java.lang.Class<T> interfaceClass)Deprecated.Provided for improved compatibility between JNA 4.X and 5.X- See Also:
load(java.lang.String, java.lang.Class)
-
loadLibrary
@Deprecated public static <T> T loadLibrary(java.lang.String name, java.lang.Class<T> interfaceClass, java.util.Map<java.lang.String,?> options)Deprecated.Provided for improved compatibility between JNA 4.X and 5.X
-
findEnclosingLibraryClass
static java.lang.Class<?> findEnclosingLibraryClass(java.lang.Class<?> cls)
Find the library interface corresponding to the given class. Checks all ancestor classes and interfaces for a declaring class which implementsLibrary.- Parameters:
cls- The given class- Returns:
- The enclosing class
-
getLibraryOptions
public static java.util.Map<java.lang.String,java.lang.Object> getLibraryOptions(java.lang.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(aMap),TYPE_MAPPER(aTypeMapper),STRUCTURE_ALIGNMENT(anInteger), andSTRING_ENCODING(aString).- Parameters:
type- The type class- Returns:
- The options map
-
getTypeMapper
public static TypeMapper getTypeMapper(java.lang.Class<?> cls)
Return the preferredTypeMapperfor the given native interface. SeeLibrary.OPTION_TYPE_MAPPER.
-
getStringEncoding
public static java.lang.String getStringEncoding(java.lang.Class<?> cls)
- Parameters:
cls- The native interface type- Returns:
- The preferred string encoding for the given native interface.
If there is no setting, defaults to the
getDefaultStringEncoding(). - See Also:
Library.OPTION_STRING_ENCODING
-
getDefaultStringEncoding
public static java.lang.String getDefaultStringEncoding()
- Returns:
- The default string encoding. Returns the value of the system
property
jna.encodingorDEFAULT_ENCODING.
-
getStructureAlignment
public static int getStructureAlignment(java.lang.Class<?> cls)
- Parameters:
cls- The native interface type- Returns:
- The preferred structure alignment for the given native interface.
- See Also:
Library.OPTION_STRUCTURE_ALIGNMENT
-
getBytes
static byte[] getBytes(java.lang.String s)
- Parameters:
s- The input string- Returns:
- A byte array corresponding to the given String. The encoding
used is obtained from
getDefaultStringEncoding().
-
getBytes
static byte[] getBytes(java.lang.String s, java.lang.String encoding)- Parameters:
s- The string. Must not benull.encoding- The encoding - ifnullthen the default platform encoding is used- Returns:
- A byte array corresponding to the given String, using the given encoding. If the encoding is not found default to the platform native encoding.
-
getBytes
static byte[] getBytes(java.lang.String s, java.nio.charset.Charset charset)- Parameters:
s- The string. Must not benull.charset- The charset used to encodes. Must not benull.- Returns:
- A byte array corresponding to the given String, using the given charset.
-
toByteArray
public static byte[] toByteArray(java.lang.String s)
- Parameters:
s- The string- Returns:
- A NUL-terminated byte buffer equivalent to the given String,
using the encoding returned by
getDefaultStringEncoding(). - See Also:
toByteArray(String, String)
-
toByteArray
public static byte[] toByteArray(java.lang.String s, java.lang.String encoding)- Parameters:
s- The string. Must not benull.encoding- The encoding - ifnullthen the default platform encoding is used- Returns:
- A NUL-terminated byte buffer equivalent to the given String, using the given encoding.
- See Also:
getBytes(String, String)
-
toByteArray
public static byte[] toByteArray(java.lang.String s, java.nio.charset.Charset charset)- Parameters:
s- The string. Must not benull.charset- The charset used to encodes. Must not benull.- Returns:
- A NUL-terminated byte buffer equivalent to the given String, using the given charset.
- See Also:
getBytes(String, String)
-
toCharArray
public static char[] toCharArray(java.lang.String s)
- Parameters:
s- The string- Returns:
- A NUL-terminated wide character buffer equivalent to the given string.
-
isUnpacked
static boolean isUnpacked(java.io.File file)
Identify temporary files unpacked from classpath jar files.
-
extractFromResourcePath
public static java.io.File extractFromResourcePath(java.lang.String name) throws java.io.IOExceptionAttempt 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 withoutPlatform.RESOURCE_PREFIX, after mapping the library name viaNativeLibrary.mapSharedLibraryName(String).- Returns:
- File indicating extracted resource on disk
- Throws:
java.io.IOException- if resource not found
-
extractFromResourcePath
public static java.io.File extractFromResourcePath(java.lang.String name, java.lang.ClassLoader loader) throws java.io.IOExceptionAttempt 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 withoutPlatform.RESOURCE_PREFIX, after mapping the library name viaNativeLibrary.mapSharedLibraryName(String).loader- Class loader to use to load resources- Returns:
- File indicating extracted resource on disk
- Throws:
java.io.IOException- if resource not found
-
getLastError
public static int getLastError()
Retrieve last error set by the OS. This corresponds toGetLastError()on Windows, anderrnoon 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
LastErrorExceptioninstead. If a method's signature includes a throw ofLastErrorException, the last error will be set to zero before the native call and aLastErrorExceptionwill 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 givenNativeLibrary. 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 java.lang.String getWebStartLibraryPath(java.lang.String libName)
If running web start, determine the location of a given native library. This value may be used to properly setjna.library.pathso that JNA can load libraries identified by the <nativelib> tag in the JNLP configuration file. Returnsnullif 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:
java.lang.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.
-
markTemporaryFile
static void markTemporaryFile(java.io.File file)
Perform cleanup of automatically unpacked native shared library.
-
getTempDir
static java.io.File getTempDir() throws java.io.IOExceptionObtain a directory suitable for writing JNA-specific temporary files. Override withjna.tmpdir- Throws:
java.io.IOException
-
removeTemporaryFiles
static void removeTemporaryFiles() throws java.io.IOExceptionRemove all marked temporary files in the given directory.- Throws:
java.io.IOException
-
getNativeSize
public static int getNativeSize(java.lang.Class<?> type, java.lang.Object value)- Parameters:
type- The Java class for which the native size is to be determinedvalue- an instance of said class (if available)- Returns:
- the native size of the given class, in bytes. For use with arrays.
-
getNativeSize
public static int getNativeSize(java.lang.Class<?> cls)
Returns the native size for a given Java class. Structures are assumed to bestructpointers unless they implementStructure.ByValue.- Parameters:
cls- The Java class- Returns:
- The native size for the class
-
isSupportedNativeType
public static boolean isSupportedNativeType(java.lang.Class<?> cls)
- Parameters:
cls- The Java class- Returns:
truewhether 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 isnull, the default handler will be reinstated.- Parameters:
eh- The default handler
-
getCallbackExceptionHandler
public static Callback.UncaughtExceptionHandler getCallbackExceptionHandler()
- Returns:
- the current handler for callback uncaught exceptions.
-
register
public static void register(java.lang.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
-
findDirectMappedClass
static java.lang.Class<?> findDirectMappedClass(java.lang.Class<?> cls)
Find the nearest enclosing class with native methods.
-
getCallingClass
static java.lang.Class<?> getCallingClass()
Try to determine the class context in which aregister(String)call was made.
-
setCallbackThreadInitializer
public static void setCallbackThreadInitializer(Callback cb, CallbackThreadInitializer initializer)
Set a thread initializer for the given callback.- Parameters:
cb- The callback to invokeinitializer- The thread initializer indicates desired thread configuration when the given Callback is invoked on a native thread not yet attached to the VM.
-
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(java.lang.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.
-
registered
public static boolean registered(java.lang.Class<?> cls)
- Parameters:
cls- The typeClass- Returns:
- whether the given class's native components are registered.
-
getSignature
static java.lang.String getSignature(java.lang.Class<?> cls)
-
replace
static java.lang.String replace(java.lang.String s1, java.lang.String s2, java.lang.String str)
-
register
public static void register(java.lang.Class<?> cls, java.lang.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 orjna.library.path.- Parameters:
cls- Class with native methods to registerlibName- name of or path to native library to which functions should be bound
-
register
public static void register(java.lang.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 registerlib- library to which functions should be bound
-
ffi_prep_cif
public static long ffi_prep_cif(int abi, int nargs, long ffi_return_type, long ffi_types)Create a new cif structure.
-
ffi_call
public static void ffi_call(long cif, long fptr, long resp, long args)Make an FFI function call.
-
ffi_prep_closure
public static long ffi_prep_closure(long cif, Native.ffi_callback cb)
-
ffi_free_closure
public static void ffi_free_closure(long closure)
-
initialize_ffi_type
static int initialize_ffi_type(long type_info)
Returns the size (calculated by libffi) of the given type.
-
main
public static void main(java.lang.String[] args)
Prints JNA library details to the console.
-
freeNativeCallback
static void freeNativeCallback(long ptr)
Free the given callback trampoline.
-
createNativeCallback
static long createNativeCallback(Callback callback, java.lang.reflect.Method method, java.lang.Class<?>[] parameterTypes, java.lang.Class<?> returnType, int callingConvention, int flags, java.lang.String encoding)
Create a native trampoline to delegate execution to the Java callback.
-
invokeInt
static int invokeInt(Function function, long fp, int callFlags, java.lang.Object[] args)
Call the native function.- Parameters:
function- Present to prevent the GC to collect the Function object prematurelyfp- function pointercallFlags- calling convention to be usedargs- Arguments to pass to the native function- Returns:
- The value returned by the target native function
-
invokeLong
static long invokeLong(Function function, long fp, int callFlags, java.lang.Object[] args)
Call the native function.- Parameters:
function- Present to prevent the GC to collect the Function object prematurelyfp- function pointercallFlags- calling convention to be usedargs- Arguments to pass to the native function- Returns:
- The value returned by the target native function
-
invokeVoid
static void invokeVoid(Function function, long fp, int callFlags, java.lang.Object[] args)
Call the native function.- Parameters:
function- Present to prevent the GC to collect the Function object prematurelyfp- function pointercallFlags- calling convention to be usedargs- Arguments to pass to the native function
-
invokeFloat
static float invokeFloat(Function function, long fp, int callFlags, java.lang.Object[] args)
Call the native function.- Parameters:
function- Present to prevent the GC to collect the Function object prematurelyfp- function pointercallFlags- calling convention to be usedargs- Arguments to pass to the native function- Returns:
- The value returned by the target native function
-
invokeDouble
static double invokeDouble(Function function, long fp, int callFlags, java.lang.Object[] args)
Call the native function.- Parameters:
function- Present to prevent the GC to collect the Function object prematurelyfp- function pointercallFlags- calling convention to be usedargs- Arguments to pass to the native function- Returns:
- The value returned by the target native function
-
invokePointer
static long invokePointer(Function function, long fp, int callFlags, java.lang.Object[] args)
Call the native function.- Parameters:
function- Present to prevent the GC to collect the Function object prematurelyfp- function pointercallFlags- calling convention to be usedargs- Arguments to pass to the native function- Returns:
- The value returned by the target native function
-
invokeStructure
static Structure invokeStructure(Function function, long fp, int callFlags, java.lang.Object[] args, Structure s)
Call the native function, returning a struct by value.- Parameters:
function- Present to prevent the GC to collect the Function object prematurelyfp- function pointercallFlags- calling convention to be usedargs- Arguments to pass to the native function- Returns:
- the passed-in Structure
-
invokeObject
static java.lang.Object invokeObject(Function function, long fp, int callFlags, java.lang.Object[] args)
Call the native function, returning a JavaObject.- Parameters:
function- Present to prevent the GC to collect the Function object prematurelyfp- function pointercallFlags- calling convention to be usedargs- Arguments to pass to the native function- Returns:
- The returned Java
Object
-
open
static long open(java.lang.String name)
Open the requested native library with default options.
-
open
static long open(java.lang.String name, int flags)Open the requested native library with the specified platform-specific otions.
-
close
static void close(long handle)
Close the given native library.
-
findSymbol
static long findSymbol(long handle, java.lang.String name)
-
indexOf
static long indexOf(Pointer pointer, long baseaddr, long offset, byte value)
-
read
static void read(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length)
-
read
static void read(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length)
-
read
static void read(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length)
-
read
static void read(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length)
-
read
static void read(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length)
-
read
static void read(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length)
-
read
static void read(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length)
-
write
static void write(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length)
-
write
static void write(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length)
-
write
static void write(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length)
-
write
static void write(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length)
-
write
static void write(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length)
-
write
static void write(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length)
-
write
static void write(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length)
-
getByte
static byte getByte(Pointer pointer, long baseaddr, long offset)
-
getChar
static char getChar(Pointer pointer, long baseaddr, long offset)
-
getShort
static short getShort(Pointer pointer, long baseaddr, long offset)
-
getInt
static int getInt(Pointer pointer, long baseaddr, long offset)
-
getLong
static long getLong(Pointer pointer, long baseaddr, long offset)
-
getFloat
static float getFloat(Pointer pointer, long baseaddr, long offset)
-
getDouble
static double getDouble(Pointer pointer, long baseaddr, long offset)
-
getPointer
static Pointer getPointer(long addr)
-
getWideString
static java.lang.String getWideString(Pointer pointer, long baseaddr, long offset)
-
getString
static java.lang.String getString(Pointer pointer, long offset)
-
getString
static java.lang.String getString(Pointer pointer, long offset, java.lang.String encoding)
-
getStringBytes
static byte[] getStringBytes(Pointer pointer, long baseaddr, long offset)
-
setMemory
static void setMemory(Pointer pointer, long baseaddr, long offset, long length, byte value)
-
setByte
static void setByte(Pointer pointer, long baseaddr, long offset, byte value)
-
setShort
static void setShort(Pointer pointer, long baseaddr, long offset, short value)
-
setChar
static void setChar(Pointer pointer, long baseaddr, long offset, char value)
-
setInt
static void setInt(Pointer pointer, long baseaddr, long offset, int value)
-
setLong
static void setLong(Pointer pointer, long baseaddr, long offset, long value)
-
setFloat
static void setFloat(Pointer pointer, long baseaddr, long offset, float value)
-
setDouble
static void setDouble(Pointer pointer, long baseaddr, long offset, double value)
-
setPointer
static void setPointer(Pointer pointer, long baseaddr, long offset, long value)
-
setWideString
static void setWideString(Pointer pointer, long baseaddr, long offset, java.lang.String value)
-
getDirectByteBuffer
static java.nio.ByteBuffer getDirectByteBuffer(Pointer pointer, long addr, long offset, long length)
-
malloc
public static long malloc(long size)
Call the real native malloc- Parameters:
size- size of the memory to be allocated- Returns:
- native address of the allocated memory block; zero if the allocation failed.
-
free
public static void free(long ptr)
Call the real native free- Parameters:
ptr- native address to be freed; a value of zero has no effect, passing an already-freed pointer will cause pain.
-
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:
java.lang.IllegalStateException- ifdetach(true)is called on a thread created by the JVM.
-
getTerminationFlag
static Pointer getTerminationFlag(java.lang.Thread t)
-
-