C struct written in a file open with Java

For example, in C, I have a structure:

typedef struct {
    int number;
    double x1;
    double y1;
    double x2;
    double y2;
    double x3;
    double y3;
} CTRstruct;`

Then I write it to a file fwrite(&tr, 1, sizeof(tr), fp);(tr is its CTRstruct var, fp is the file pointer);

Then I need to read it using Java! I really don’t know how to read the structure from a file ... I tried to read it using ObjectInputStream(), the last idea is to read using RandomAccessFile(), but I also don’t know how ... ( readLong(), readDouble()also does not work, it works with the source, but does not read correct data). So, any idea how to read C struct from binary with Java?


If this is interesting, my version reads an integer (but it is ugly, and I don't know what to do with double):

Public class MyDataInputStream extends DataInputStream {

public MyDataInputStream(InputStream AIs) {
    super(AIs);
}

public int readInt1() throws IOException{
    int ch1 = in.read();
    int ch2 = in.read();
    int ch3 = in.read();
    int ch4 = in.read();
    if ((ch1 | ch2 | ch3 | ch4) < 0)
        throw new EOFException();
    return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
}

(, int (8bytes), double native func).

+3
5

, C (int, double) endianness (thanks andrew cooke) , , Java.

+2

fwrite struct, . struct , , , .. " "!

, JSON - .

+5

. Java. , .

+4

DataInputStream - Java - ,

int number = dataInputStream.readInt();
double x1 = dataInputStream.readDouble();
...
double y3 = dataInputStream.readDouble();

100%, .

+1

Well, in the unlikely event that JNI is an option for you, you can read it back to C. Using swig , you can easily expose your structure along with its function to read from a file. Of course, all the problems associated with JNI are not worth the problem alone, but you may already be using it.

+1
source

All Articles