Re: Reading a C struct in java
Mark wrote:
Hi,
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)?
I expect this to map most directly to four byte[] arrays in Java.
Here's an idea for a method that might be useful:
***** DANGER! DANGER! UNTESTED CODE AHEAD *****
public byte[][] getRaw(InputStream in, int... sizes) throws IOException{
byte[][] result = new byte[sizes.length][];
for(int i=0; i<sizes.length; i++){
result[i] = new byte[sizes[i]];
in.read(result[i]);
}
return result;
}
If I've got this right, the result of calling:
getRaw(in, 1, 6, 1, 1)
should be a four element array of byte[], with each element containing
the raw data from one of the fields. That could be used, for example, as
a constructor parameter for a class that represents type_t in Java, with
each fields converted to a more useful type. For example, if duplicate
is logically a boolean, the class would have a boolean field,
initialized according to how the C char represents booleans.
Patricia