how to convert c struct to java classes

W

warrior

1) how to convert c struct to java classes
2) How do i code the function pointers wriiten in c to java?
 
M

markspace

warrior said:
1) how to convert c struct to java classes


Use a class. Consider giving it public members to mimic the
accessibility of C structs, but also consider giving it private
variables and public accessors and mutator methods.

2) How do i code the function pointers wriiten in c to java?

The easiest is to just use the reference to the object, which you
already have. All objects in Java that you deal with are actually
"pointers" (references) anyway, you have no choice but to use a "pointer."

In some instances, you may wish to define an interface or use
reflection. This sounds a bit advanced for you right now, I'd try the
reference described above first.
 
A

Arne Vajhøj

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,227
Latest member
Daniella65

Latest Threads

Top