Re: how to convert c struct to java classes
On 23-12-2009 05:03, warrior wrote:
1) how to convert c struct to java classes
Multiple ways.
DataInputStream wrapped around a ByteArrayInputStream wrapped
around the byte array.
NIO ByteBuffer wrapped around the byte array.
More custom solution. Example:
import dk.vajhoej.record.Alignment;
import dk.vajhoej.record.Endian;
import dk.vajhoej.record.FieldType;
import dk.vajhoej.record.Struct;
import dk.vajhoej.record.StructField;
/*
* struct data
* {
* long int liv;
* int bv1 : 4;
* int bv2 : 4;
* short int siv;
* };
*
* With a compiler and settings that uses little endian, natural
* alignment, sizeof(long)=4, sizeof(short)=2 etc..
*/
@Struct(endianess=Endian.LITTLE, alignment=Alignment.NATURAL)
public class Data {
@StructField(n=0,type=FieldType.INT4)
private int liv;
@StructField(n=1,type=FieldType.BIT,length=4)
private int bv1;
@StructField(n=2,type=FieldType.BIT,length=4)
private int bv2;
@StructField(n=3,type=FieldType.INT2)
private int siv;
public int getLiv() {
return liv;
}
public int getBv1() {
return bv1;
}
public int getBv2() {
return bv2;
}
public int getSiv() {
return siv;
}
}
import dk.vajhoej.record.RecordException;
import dk.vajhoej.record.StructReader;
public class CStruct {
public static void main(String[] args) throws RecordException {
byte[] b = { 7, 0, 0, 0, 0x12, 0, 3, 0 };
StructReader sr = new StructReader(b);
Data o = sr.read(Data.class);
System.out.println(o.getLiv() + " " + o.getBv1() + " " +
o.getBv2() + " " + o.getSiv());
}
}
2) How do i code the function pointers wriiten in c to java?
The Java way is to have sub classes that overrides a certain
method with the implementation you need.
Arne