public abstract class Structure extends Object
struct*
. When used as a field within another
Structure
, it corresponds to struct
. The
tagging interfaces Structure.ByReference
and Structure.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(java.lang.Class<?>)
and Native.getTypeMapper(java.lang.Class<?>)
.
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 define getFieldOrder()
to return a List of
field names (Strings) indicating the proper order of the fields. 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:
volatile
JNA will not write the field unless specifically
instructed to do so via writeField(String)
. This allows you to
prevent inadvertently overwriting memory that may be updated in real time
on another (possibly native) thread.
final
JNA will overwrite the field via read()
,
but otherwise the field is not modifiable from Java. Take care when using
this option, since the compiler will usually assume all accesses
to the field (for a given Structure instance) have the same value. This
modifier is invalid to use on J2ME.
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.
Modifier and Type | Class and Description |
---|---|
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. |
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. |
(package private) static class |
Structure.FFIType
This class auto-generates an ffi_type structure appropriate for a given
structure for use by libffi.
|
protected static class |
Structure.StructField |
(package private) static class |
Structure.StructureSet
Avoid using a hash-based implementation since the hash code
for a Structure is not immutable.
|
Modifier and Type | Field and Description |
---|---|
static int |
ALIGN_DEFAULT
Use the platform default alignment.
|
static int |
ALIGN_GNUC
validated for 32-bit x86 linux/gcc; align field size, max 4 bytes
|
static int |
ALIGN_MSVC
validated for w32/msvc; align on field size
|
static int |
ALIGN_NONE
No alignment, place all fields on nearest 1-byte boundary
|
protected static int |
CALCULATE_SIZE
Align to an 8-byte boundary.
|
(package private) static Map<Class<?>,List<String>> |
fieldOrder |
(package private) static Map<Class<?>,com.sun.jna.Structure.LayoutInfo> |
layoutInfo |
Modifier | Constructor and Description |
---|---|
protected |
Structure() |
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) |
protected |
Structure(TypeMapper mapper) |
Modifier and Type | Method and Description |
---|---|
protected void |
allocateMemory()
Attempt to allocate memory if sufficient information is available.
|
protected void |
allocateMemory(int size)
Provided for derived classes to indicate a different
size than the default.
|
protected Memory |
autoAllocate(int size)
Obtain auto-allocated memory for use with struct represenations.
|
void |
autoRead() |
static void |
autoRead(Structure[] ss) |
void |
autoWrite() |
static void |
autoWrite(Structure[] ss) |
(package private) static Set<Structure> |
busy() |
protected void |
cacheTypeInfo(Pointer p)
Cache native type information for use in native code.
|
protected int |
calculateSize(boolean force)
Calculate the amount of native memory required for this structure.
|
(package private) int |
calculateSize(boolean force,
boolean avoidFFIType) |
void |
clear()
Clears the native memory associated with this Structure.
|
(package private) void |
conditionalAutoRead()
Performs auto-read only if uninitialized.
|
static List<String> |
createFieldsOrder(List<String> baseFields,
List<String> extraFields) |
static List<String> |
createFieldsOrder(List<String> baseFields,
String... extraFields) |
static List<String> |
createFieldsOrder(String... fields) |
static List<String> |
createFieldsOrder(String field) |
boolean |
dataEquals(Structure s)
Return whether the given Structure's native backing data is identical to
this one.
|
boolean |
dataEquals(Structure s,
boolean clear)
Return whether the given Structure's backing data is identical to
this one, optionally clearing and re-writing native memory before checking.
|
protected void |
ensureAllocated()
Ensure this memory has its size and layout calculated and its
memory allocated.
|
boolean |
equals(Object o) |
protected int |
fieldOffset(String name)
Returns the calculated offset of the given field.
|
(package private) Map<String,Structure.StructField> |
fields()
Return all fields in this structure (ordered).
|
boolean |
getAutoRead()
Returns whether the structure is read from native memory after
a native function call.
|
boolean |
getAutoWrite()
Returns whether the structure is written to native memory prior to a native
function call.
|
protected List<Field> |
getFieldList()
Look up all fields in this class and superclasses.
|
protected abstract List<String> |
getFieldOrder()
Return this Structure's field names in their proper order.
|
protected List<Field> |
getFields(boolean force)
Returns all field names (sorted) provided so far by
getFieldOrder() |
(package private) Pointer |
getFieldTypeInfo(Structure.StructField f)
Override to supply native type information for the given field.
|
(package private) Object |
getFieldValue(Field field)
Obtain the value currently in the Java field.
|
protected int |
getNativeAlignment(Class<?> type,
Object value,
boolean isFirstElement)
Overridable in subclasses.
|
protected int |
getNativeSize(Class<?> nativeType)
Return the native size of the given Java type, from the perspective of
this Structure.
|
protected int |
getNativeSize(Class<?> nativeType,
Object value)
Return the native size of the given Java type, from the perspective of
this Structure.
|
Pointer |
getPointer()
Return a
Pointer object to this structure. |
protected String |
getStringEncoding()
Encoding to use to convert
String to native const
char* . |
protected int |
getStructAlignment() |
(package private) Pointer |
getTypeInfo() |
(package private) static Pointer |
getTypeInfo(Object obj)
Exposed for testing purposes only.
|
(package private) TypeMapper |
getTypeMapper() |
int |
hashCode() |
static Structure |
newInstance(Class<?> type)
Create a new Structure instance of the given type
|
static Structure |
newInstance(Class<?> type,
Pointer init)
Create a new Structure instance of the given type, initialized with
the given memory.
|
void |
read()
Reads the fields of the struct from native memory
|
Object |
readField(String name)
Force a read of the given field from native memory.
|
protected Object |
readField(Structure.StructField structField)
Read the given field and return its value.
|
(package private) static Map<Pointer,Structure> |
reading() |
protected void |
setAlignType(int alignType)
Change the alignment of this structure.
|
void |
setAutoRead(boolean auto)
Set whether the structure is read from native memory after
a native function call.
|
void |
setAutoSynch(boolean auto)
Set whether the structure is automatically synchronized to native memory
before and after a native function call.
|
void |
setAutoWrite(boolean auto)
Set whether the structure is written to native memory prior to a native
function call.
|
protected void |
setFieldOrder(String[] fields)
Deprecated.
Use the required method getFieldOrder() instead to
indicate the order of fields in this structure.
|
(package private) void |
setFieldValue(Field field,
Object value) |
protected void |
setStringEncoding(String encoding)
Set the desired encoding to use when writing String fields to native
memory.
|
int |
size()
Returns the size in memory occupied by this Structure.
|
(package private) static int |
size(Class<?> type)
Efficiently calculate the size of the given Structure subclass.
|
(package private) static int |
size(Class<?> type,
Structure value)
Efficiently calculate the size of the given Structure subclass.
|
protected void |
sortFields(List<Field> fields,
List<String> names)
Sort the structure fields according to the given array of names.
|
Structure[] |
toArray(int size)
Returns a view of this structure's memory as an array of structures.
|
Structure[] |
toArray(Structure[] array)
Returns a view of this structure's memory as an array of structures.
|
String |
toString()
If
jna.dump_memory is true, will include a native memory dump
of the Structure's backing memory. |
String |
toString(boolean debug) |
(package private) Structure.StructField |
typeInfoField()
Keep track of the largest aggregate field of the union to use for
FFI type information.
|
(package private) static Structure |
updateStructureByReference(Class<?> type,
Structure s,
Pointer address)
Only keep the original structure if its native address is unchanged.
|
protected void |
useMemory(Pointer m)
Set the memory used by this structure.
|
protected void |
useMemory(Pointer m,
int offset)
Set the memory used by this structure.
|
(package private) void |
useMemory(Pointer m,
int offset,
boolean force)
Set the memory used by this structure.
|
(package private) static void |
validate(Class<?> cls)
Indicate whether the given Structure class can be created by JNA.
|
void |
write()
Writes the fields of the struct to native memory
|
void |
writeField(String name)
Write the given field to native memory.
|
void |
writeField(String name,
Object value)
Write the given field value to the field and native memory.
|
protected void |
writeField(Structure.StructField structField) |
public static final int ALIGN_DEFAULT
public static final int ALIGN_NONE
public static final int ALIGN_GNUC
public static final int ALIGN_MSVC
protected static final int CALCULATE_SIZE
protected Structure()
protected Structure(TypeMapper mapper)
protected Structure(int alignType)
protected Structure(int alignType, TypeMapper mapper)
protected Structure(Pointer p)
protected Structure(Pointer p, int alignType)
protected Structure(Pointer p, int alignType, TypeMapper mapper)
Map<String,Structure.StructField> fields()
ensureAllocated()
must be called prior to
calling this method.Map
of field names to field representations.TypeMapper getTypeMapper()
protected void setStringEncoding(String encoding)
encoding
- desired encodingprotected String getStringEncoding()
String
to native const
char*
. Defaults to Native.getDefaultStringEncoding()
.protected void setAlignType(int alignType)
ALIGN_DEFAULT
, the default
alignment for the defining class will be used.alignType
- desired alignment typeprotected Memory autoAllocate(int size)
size
- desired sizeprotected void useMemory(Pointer m)
m
- Memory to with which to back this Structure
.protected void useMemory(Pointer m, int offset)
m
- Base memory to use to back this structure.offset
- offset into provided memory where structure mapping
should start.void useMemory(Pointer m, int offset, boolean force)
m
- Native pointeroffset
- offset from pointer to useforce
- 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.protected void ensureAllocated()
protected void allocateMemory()
protected void allocateMemory(int size)
size
- how much memory to allocatepublic int size()
public void clear()
public Pointer getPointer()
Pointer
object to this structure. Note that if you
use the structure's pointer as a function argument, you are responsible
for calling write()
prior to the call and read()
after the call. These calls are normally handled automatically by the
Function
object when it encounters a Structure
argument
or return value.
The returned pointer may not have meaning for Structure.ByValue
structure representations.void conditionalAutoRead()
public void read()
protected int fieldOffset(String name)
name
- field to examinepublic Object readField(String name)
name
- field to be readIllegalArgumentException
- if no field exists with the given nameObject getFieldValue(Field field)
field
- field to look upvoid setFieldValue(Field field, Object value)
field
- field to setvalue
- value to setstatic Structure updateStructureByReference(Class<?> type, Structure s, Pointer address)
type
- Structure subclasss
- Original Structure objectaddress
- the native struct *
Structure.ByReference
objectprotected Object readField(Structure.StructField structField)
structField
- field to be readpublic void write()
public void writeField(String name)
name
- which field to synchIllegalArgumentException
- if no field exists with the given namepublic void writeField(String name, Object value)
name
- field to writevalue
- value to writeIllegalArgumentException
- if no field exists with the given nameprotected void writeField(Structure.StructField structField)
structField
- internal field representation to synch to native memoryprotected abstract List<String> getFieldOrder()
protected List getFieldOrder() {
return Arrays.asList(new String[] { ... });
}
IMPORTANT
When deriving from an existing Structure subclass, ensure that
you augment the list provided by the superclass, e.g.
protected List getFieldOrder() {
List fields = new ArrayList(super.getFieldOrder());
fields.addAll(Arrays.asList(new String[] { ... }));
return fields;
}
Field order must be explicitly indicated, since the
field order as returned by Class.getFields()
is not
guaranteed to be predictable.@Deprecated protected final void setFieldOrder(String[] fields)
fields
- ordered array of field namesprotected void sortFields(List<Field> fields, List<String> names)
fields
- list of fields to be sortednames
- list of names representing the desired sort orderprotected List<Field> getFieldList()
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> createFieldsOrder(String field)
field
- The (single) field namepublic static List<String> createFieldsOrder(String... fields)
fields
- The structure field names in correct orderprotected List<Field> getFields(boolean force)
getFieldOrder()
force
- set if results are required immediatelyError
- if force is true and field order data not yet specified
and can't be generated automatically.protected int calculateSize(boolean force)
CALCULATE_SIZE
if the size can not yet be
determined (usually due to fields in the derived class not yet
being initialized).
If the force
parameter is true
will throw
an IllegalStateException
if the size can not be determined.force
- whether to force size calculationCALCULATE_SIZE
if the size can not
yet be determined.IllegalStateException
- an array field is not initialized or the
size can not be determined while force
is true
.IllegalArgumentException
- when an unsupported field type is
encounteredstatic int size(Class<?> type)
type
- Structure subclass to checkstatic int size(Class<?> type, Structure value)
type
- Structure subclass to checkvalue
- optional instance of the given classint calculateSize(boolean force, boolean avoidFFIType)
force
- whether to force size calculation.avoidFFIType
- set false in certain situations to avoid recursive
type lookup.CALCULATE_SIZE
if there is not yet
enough information to perform the size calculation.protected int getStructAlignment()
protected int getNativeAlignment(Class<?> type, Object value, boolean isFirstElement)
type
- field typevalue
- field value, if availableisFirstElement
- is this field the first element in the struct?public String toString()
jna.dump_memory
is true, will include a native memory dump
of the Structure's backing memory.public String toString(boolean debug)
debug
- If true, will include a native memory dump of the
Structure's backing memory.public Structure[] toArray(Structure[] array)
Structure
must have a public, no-arg
constructor. If the structure is currently using auto-allocated
Memory
backing, the memory will be resized to fit the entire
array.array
- Structure[] object to populatepublic Structure[] toArray(int size)
Structure
must have a public, no-arg
constructor. If the structure is currently using auto-allocated
Memory
backing, the memory will be resized to fit the entire
array.size
- desired number of elementspublic boolean dataEquals(Structure s)
s
- Structure to comparepublic boolean dataEquals(Structure s, boolean clear)
s
- Structure to compareclear
- whether to clear native memorypublic boolean equals(Object o)
public int hashCode()
protected void cacheTypeInfo(Pointer p)
p
- Native pointer to the type informationPointer getFieldTypeInfo(Structure.StructField f)
f
- internal field representationPointer getTypeInfo()
public void setAutoSynch(boolean auto)
boolean auto = ...;
setAutoRead(auto);
setAutoWrite(auto);
For extremely large or complex structures where you only need to
access a small number of fields, you may see a significant performance
benefit by avoiding automatic structure reads and writes. If
auto-read and -write are disabled, it is up to you to ensure that the
Java fields of interest are synched before and after native function
calls via readField(String)
and writeField(String,Object)
.
This is typically most effective when a native call populates a large
structure and you only need a few fields out of it. After the native
call you can call readField(String)
on only the fields of
interest.auto
- whether to automatically synch with native memory.public void setAutoRead(boolean auto)
auto
- whether to automatically synch from native memory.public boolean getAutoRead()
public void setAutoWrite(boolean auto)
auto
- whether to automatically synch to native memory.public boolean getAutoWrite()
static Pointer getTypeInfo(Object obj)
obj
- object to querypublic static Structure newInstance(Class<?> type, Pointer init) throws IllegalArgumentException
type
- desired Structure typeinit
- initial memoryIllegalArgumentException
- if the instantiation failspublic static Structure newInstance(Class<?> type) throws IllegalArgumentException
type
- desired Structure typeIllegalArgumentException
- if the instantiation failsStructure.StructField typeInfoField()
public static void autoRead(Structure[] ss)
public void autoRead()
public static void autoWrite(Structure[] ss)
public void autoWrite()
protected int getNativeSize(Class<?> nativeType)
nativeType
- field type to examineprotected int getNativeSize(Class<?> nativeType, Object value)
nativeType
- field type to examinevalue
- instance of the field typestatic void validate(Class<?> cls)
cls
- Structure subclass to check