Top Description Inners Fields Constructors Methods
com.sun.jna

public abstract Class Structure

extends Object
Class Inheritance
Known Direct Subclasses
com.sun.jna.Structure.FFIType, com.sun.jna.Union, com.sun.jna.CallbackReference.AttachOptions
Imports
java.lang.annotation.Documented, .ElementType, .Retention, .RetentionPolicy, .Target, java.lang.reflect.Array, .Constructor, .Field, .InvocationTargetException, .Modifier, java.nio.Buffer, java.util.AbstractCollection, .ArrayList, .Arrays, .Collection, .Collections, .HashMap, .HashSet, .Iterator, .LinkedHashMap, .LinkedList, .List, .Map, .Set, .WeakHashMap, java.util.logging.Level, .Logger

Represents a native structure with a Java peer class. When used as a function parameter or return value, this class corresponds to struct*. When used as a field within another Structure, it corresponds to struct. The tagging interfaces ByReference and ByValue may be used to alter the default behavior. Structures may have variable size, but only by providing an array field (e.g. byte[]).

See the overview for supported type mappings for struct fields.

Structure alignment and type mappings are derived by default from the enclosing interface definition (if any) by using Native#getStructureAlignment and Native#getTypeMapper. Alternatively you can explicitly provide alignment, field order, or type mapping by calling the respective Structure functions in your subclass's constructor.

Structure fields corresponding to native struct fields must be public. If your structure is to have no fields of its own, it must be declared abstract.

You must annotate the class with FieldOrder or implement getFieldOrder, whichever you choose it must contain the field names (Strings) indicating the proper order of the fields. If you chose to implement getFieldOrder notice that when dealing with multiple levels of subclasses of Structure, you must add to the list provided by the superclass getFieldOrder the fields defined in the current class.

In the past, most VMs would return them in a predictable order, but the JVM spec does not require it, so getFieldOrder is now required to ensure JNA knows the proper order).

Structure fields may additionally have the following modifiers:

Note

Strings are used to represent native C strings because usage of char * is generally more common than wchar_t *. You may provide a type mapper (example here) if you prefer to use String in place of WString if your native code predominantly uses wchar_t *.

Note

In general, instances of this class are not synchronized.

Authors
Todd Fast, [email protected], [email protected]

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
public static interface
Structure.ByReference

Tagging interface to indicate the address of an instance of the Structure type is to be used within a Structure definition rather than nesting the full Structure contents.

public static interface
Structure.ByValue

Tagging interface to indicate the value of an instance of the Structure type is to be used in function invocations rather than its address.

pack-priv static class
Structure.FFIType

This class auto-generates an ffi_type structure appropriate for a given structure for use by libffi.

public static @interface
Structure.FieldOrder

Used to declare fields order as metadata instead of method.

private static class
Structure.LayoutInfo

Keep track of structure layout information.

private static class
Structure.NativeStringTracking

A class to keep NativeString instances alive and avoid writing the same value again and again

protected static class
pack-priv static class
Structure.StructureSet

Avoid using a hash-based implementation since the hash code for a Structure is not immutable.

Field Summary

Modifier and TypeField and Description
private int
public static final int
ALIGN_DEFAULT

Use the platform default alignment.

public static final int
ALIGN_GNUC

validated for 32-bit x86 linux/gcc; align field size, max 4 bytes

public static final int
ALIGN_MSVC

validated for w32/msvc; align on field size

public static final int
ALIGN_NONE

No alignment, place all fields on nearest 1-byte boundary

private int
private Structure[]
private boolean
private boolean
private static final ThreadLocal<Set<Structure>>
protected static final int
CALCULATE_SIZE

Align to an 8-byte boundary.

private String
pack-priv static final Map<Class<?>, List<String>>
pack-priv static final Map<Class<?>, Structure.LayoutInfo>
private static final Logger
private Pointer
private final Map<String, Structure.NativeStringTracking>
private static final Pointer
PLACEHOLDER_MEMORY

Placeholder pointer to help avoid auto-allocation of memory where a Structure needs a valid pointer but want to avoid actually reading from it.

private boolean
private static final ThreadLocal<Map<Pointer, Structure>>
private int
private int
private Map<String, Structure.StructField>
private long
private TypeMapper

Constructor Summary

AccessConstructor and Description
protected
protected
protected
Structure(int alignType)

protected
Structure(int alignType, TypeMapper mapper)

protected
Structure(Pointer p)

Create a structure cast onto pre-allocated memory.

protected
Structure(Pointer p, int alignType)

protected
Structure(Pointer p, int alignType, TypeMapper mapper)

Method Summary

Modifier and TypeMethod and Description
private int
addPadding(int calculatedSize)

private int
addPadding(int calculatedSize, int alignment)

protected void
allocateMemory()

Attempt to allocate memory if sufficient information is available.

private void
allocateMemory(boolean avoidFFIType)

protected void
allocateMemory(int
how much memory to allocate
size
)

Provided for derived classes to indicate a different size than the default.

protected Memory

Returns:

newly-allocated memory
autoAllocate
(int
desired size
size
)

Obtain auto-allocated memory for use with struct represenations.

public static void
public void
public static void
public void
private Class<?>
pack-priv static Set<Structure>
busy()

protected void
cacheTypeInfo(Pointer
Native pointer to the type information
p
)

Cache native type information for use in native code.

protected int

Returns:

calculated size, or CALCULATE_SIZE if the size can not yet be determined.
calculateSize
(boolean
whether to force size calculation
force
)

Calculate the amount of native memory required for this structure.

pack-priv int

Returns:

calculated size, or CALCULATE_SIZE if there is not yet enough information to perform the size calculation.
calculateSize
(boolean
whether to force size calculation.
force
,
boolean
set false in certain situations to avoid recursive type lookup.
avoidFFIType
)

public void
clear()

Clears the native memory associated with this Structure.

pack-priv void
conditionalAutoRead()

Performs auto-read only if uninitialized.

public static List<String>
createFieldsOrder(List<String> baseFields, String... extraFields)

public static List<String>
createFieldsOrder(List<String> baseFields, List<String> extraFields)

public static List<String>

Returns:

@return An un-modifiable list containing the field name
createFieldsOrder
(String
The (single) field name
field
)

public static List<String>

Returns:

An un-modifiable list of the fields
createFieldsOrder
(String...
The structure field names in correct order
fields
)

public boolean

Returns:

equality result
dataEquals
(Structure
Structure to compare
s
)

Return whether the given Structure's native backing data is identical to this one.

public boolean

Returns:

equality result
dataEquals
(Structure
Structure to compare
s
,
boolean
whether to clear native memory
clear
)

Return whether the given Structure's backing data is identical to this one, optionally clearing and re-writing native memory before checking.

private Structure.LayoutInfo
deriveLayout(boolean force, boolean avoidFFIType)

Calculates the size, alignment, and field layout of this structure.

protected void
ensureAllocated()

Ensure this memory has its size and layout calculated and its memory allocated.

private void
ensureAllocated(boolean
used when computing FFI type information to avoid recursion
avoidFFIType
)

Ensure this memory has its size and layout calculated and its memory allocated.

public boolean

Returns:

whether the given structure's type and pointer match.
equals
(Object
the reference object with which to compare.
o
)

Overrides java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.
protected int

Returns:

return offset of the given field
fieldOffset
(String
field to examine
name
)

Returns the calculated offset of the given field.

private List<String>

Returns:

(cached) ordered list of fields
fieldOrder
()

Cache field order per-class.

pack-priv Map<String, Structure.StructField>

Returns:

Map of field names to field representations.
fields
()

Return all fields in this structure (ordered).

private String
format(Class<?> type)

public boolean

Returns:

whether automatic synch from native memory is enabled.
getAutoRead
()

Returns whether the structure is read from native memory after a native function call.

public boolean

Returns:

whether automatic synch to native memory is enabled.
getAutoWrite
()

Returns whether the structure is written to native memory prior to a native function call.

protected List<Field>

Returns:

ordered list of public java.lang.reflect.Field available on this Structure class.
getFieldList
()

Look up all fields in this class and superclasses.

protected List<String>

Returns:

ordered list of field names
getFieldOrder
()

Returns this Structure's field names in their proper order.

protected List<Field>

Returns:

null if not yet able to provide fields, and force is false.
getFields
(boolean
set if results are required immediately
force
)

Returns all field names (sorted) provided so far by getFieldOrder

pack-priv Structure.FFIType

Returns:

Native pointer to the corresponding type information
getFieldTypeInfo
(Structure.StructField
internal field representation
f
)

Override to supply native type information for the given field.

pack-priv Object

Returns:

current field value (Java-side only)
getFieldValue
(Field
field to look up
field
)

Obtain the value currently in the Java field.

protected int

Returns:

the native byte alignment
getNativeAlignment
(Class<?>
field type
type
,
Object
field value, if available
value
,
boolean
is this field the first element in the struct?
isFirstElement
)

Overridable in subclasses.

protected int

Returns:

native size (in bytes) of the requested field type
getNativeSize
(Class<?>
field type to examine
nativeType
)

Return the native size of the given Java type, from the perspective of this Structure.

protected int

Returns:

native size (in bytes) of the requested field type
getNativeSize
(Class<?>
field type to examine
nativeType
,
Object
instance of the field type
value
)

Return the native size of the given Java type, from the perspective of this Structure.

public Pointer

Returns:

Native pointer representation of this structure.
getPointer
()

Return a Pointer object to this structure.

private static <
the type
T
>
Constructor<T>

Returns:

a constructor with a single Pointer argument, null if none is found
getPointerConstructor
(Class<T>
the class
type
)

Returns a constructor for the given type with a single Pointer argument, null if no such constructor is found.

protected String

Returns:

Current encoding
getStringEncoding
()

Encoding to use to convert String to native const char*.

protected int

Returns:

current alignment setting for this structure
getStructAlignment
()

pack-priv Pointer

Returns:

native type information for this structure.
getTypeInfo
()

pack-priv static Structure.FFIType

Returns:

native pointer to type information
getTypeInfo
(Object
object to query
obj
)

Exposed for testing purposes only.

pack-priv TypeMapper

Returns:

the type mapper in effect for this Structure.
getTypeMapper
()

public int

Returns:

hash code for this structure's pointer.
hashCode
()

Overrides java.lang.Object.hashCode.

Returns a hash code value for the object.
private Object
initializeField(Field field, Class<?> type)

private void
initializeFields()

Initialize any null-valued fields that should have a non-null default value.

private void
initializeTypeMapper(TypeMapper
Find the type mapper appropriate for this structure's context if none was explicitly set.
mapper
)

Initialize the type mapper for this structure.

private void
layoutChanged()

Call whenever a Structure setting is changed which might affect its memory layout.

private static <T extends Structure> T
newInstance(Class<T> type, long init)

Called from native code only; same as newInstance(Class, Pointer), except that it additionally calls conditionalAutoRead().

public static <T extends Structure> T

Returns:

the new instance
newInstance
(Class<T>
desired Structure type
type
,
Pointer
initial memory
init
)

Create a new Structure instance of the given type, initialized with the given memory.

public static <T extends Structure> T

Returns:

the new instance
newInstance
(Class<T>
desired Structure type
type
)

Create a new Structure instance of the given type

public void
read()

Reads the fields of the struct from native memory

public Object

Returns:

the new field value, after updating
readField
(String
field to be read
name
)

Force a read of the given field from native memory.

protected Object

Returns:

value of the requested field
readField
(Structure.StructField
field to be read
structField
)

Read the given field and return its value.

pack-priv static Map<Pointer, Structure>
protected void
setAlignType(int
desired alignment type
alignType
)

Change the alignment of this structure.

public void
setAutoRead(boolean
whether to automatically synch from native memory.
auto
)

Set whether the structure is read from native memory after a native function call.

public void
setAutoSynch(boolean
whether to automatically synch with native memory.
auto
)

Set whether the structure is automatically synchronized to native memory before and after a native function call.

public void
setAutoWrite(boolean
whether to automatically synch to native memory.
auto
)

Set whether the structure is written to native memory prior to a native function call.

pack-priv void
setFieldValue(Field
field to set
field
,
Object
value to set
value
)

private void
setFieldValue(Field field, Object value, boolean overrideFinal)

protected void
setStringEncoding(String
desired encoding
encoding
)

Set the desired encoding to use when writing String fields to native memory.

public int

Returns:

Native size of this structure, in bytes.
size
()

Returns the size in memory occupied by this Structure.

pack-priv static int

Returns:

native size of the given Structure subclass
size
(Class<? extends Structure>
Structure subclass to check
type
)

Efficiently calculate the size of the given Structure subclass.

pack-priv static <T extends Structure> int

Returns:

native size of the Structure subclass
size
(Class<T>
Structure subclass to check
type
,
T
optional instance of the given class
value
)

Efficiently calculate the size of the given Structure subclass.

private static <T extends Comparable<T>> List<T>
sort(Collection<? extends T> c)

protected void
sortFields(List<Field>
list of fields to be sorted
fields
,
List<String>
list of names representing the desired sort order
names
)

Sort the structure fields according to the given array of names.

private static void
public Structure[]

Returns:

array of Structure mapped onto the available memory
toArray
(Structure[]
Structure[] object to populate
array
)

Returns a view of this structure's memory as an array of structures.

public Structure[]

Returns:

array of Structure (individual elements will be of the appropriate type, as will the Structure[]).
toArray
(int
desired number of elements
size
)

Returns a view of this structure's memory as an array of structures.

public String

Returns:

String representation of this object.
toString
()

Overrides java.lang.Object.toString.

If jna.dump_memory is true, will include a native memory dump of the Structure's backing memory.
public String

Returns:

String representation of this object.
toString
(boolean
If true, will include a native memory dump of the Structure's backing memory.
debug
)

private String
toString(int indent, boolean showContents, boolean dumpMemory)

pack-priv static <T extends Structure> T

Returns:

Updated Structure.ByReference object
updateStructureByReference
(Class<T>
Structure subclass
type
,
T
Original Structure object
s
,
Pointer
the native struct *
address
)

Only keep the original structure if its native address is unchanged.

protected void
useMemory(Pointer
Memory to with which to back this Structure.
m
)

Set the memory used by this structure.

protected void
useMemory(Pointer
Base memory to use to back this structure.
m
,
int
offset into provided memory where structure mapping should start.
offset
)

Set the memory used by this structure.

pack-priv void
useMemory(Pointer
Native pointer
m
,
int
offset from pointer to use
offset
,
boolean
ByValue structures normally ignore requests to use a different memory offset; this input is set true when setting a ByValue struct that is nested within another struct.
force
)

Set the memory used by this structure.

pack-priv static void
validate(Class<? extends Structure>
Structure subclass to check
cls
)

Indicate whether the given Structure class can be created by JNA.

private void
validateField(String name, Class<?> type)

private void
validateFields()

ensure all fields are of valid type.

public void
write()

Writes the fields of the struct to native memory

public void
writeField(String
which field to synch
name
)

Write the given field to native memory.

public void
writeField(String
field to write
name
,
Object
value to write
value
)

Write the given field value to the field and native memory.

protected void
writeField(Structure.StructField
internal field representation to synch to native memory
structField
)

private void
writeField(Structure.StructField
internal field representation to synch to native memory
structField
,
Object
value to write
value
)

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait