Re: Reading a C struct in java
On Sep 29, 1:10 pm, Mark <i...@dontgetlotsofspamanymore.invalid>
wrote:
On Tue, 29 Sep 2009 11:33:29 +0200, Lothar Kimmeringer
<news200...@kimmeringer.de> wrote:
Mark wrote:
I am writing an app in java which reads data from a socket from a C
language program. The data is encoded as a C struct of char arrays
something like this;
typedef struct {
char type[1];
char length[6];
char acknowledge[1];
char duplicate[1];
...
} type_t;
How can I decode a structure like this in Java without using JNI (a
requirement)?
Do you need a parser creating Java-classes or do you simply
want to read in the data?
I don't want a parser. The exact structure is known at compile time.
....by the C compiler, and by you. However since a C struct is really
an unstructured byte array, you need a parser to extract its parts, or
if you prefer a Java class with methods like
public char getType() {
return (char) myStructArray[0];
}
public void setType(char c) {
myStructArray[0] = (byte) c;
}
If the latter you have to find out
the endianess of the system if you have to read in data consisting
of more than one byte (e.g. int) and how many bytes an int
has (varies in dependence of the processor architecture).
Endian-ness is not an issue. All the fields are char arrays.
The rest can be done with simply reading in from the stream
I don't have access to the stream. The data arrives to my code in
already in a byte array.
You can create a stream that reads from a byte array:
java.io.ByteArrayInputStream.
I guess I want to know if there is an easy way to map the C structure
to a java class or whether I will have to dissect the byte array
completely manually.
The second one you said. In Java, you have no way to know how classes
are laid out in memory, and you cannot take a byte array and interpret
it as a Java object like C does.
What you could do in principle - if you had to map a huge number of C
structs - would be to write a translator that, statically, read the
struct declarations from C code and automatically generated Java
classes with methods to parse the structures and access their fields.
Alessio