Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct written in file, open with Java

Tags:

java

c++

c

For example in C I have structure:

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

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

Then I need to read it with Java! I really don't know how to read struct from file... I tried to read it with ObjectInputStream(), last idea is to read with RandomAccessFile() but I also don't know how to... (readLong(), readDouble() also doesn't work, it works ofcource but doesn't read correct data). So, any idea how to read C struct from binary file with Java?


If it's interesting, my version to read integer (but it's ugly, & 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));
}

with double we can deal the same way (like with int or with long (8bytes) & then convert to double with native func).

like image 234
DaunnC Avatar asked Dec 13 '22 03:12

DaunnC


2 Answers

You should not use fwrite of the entire struct, because you will inevitably run into issues with padding and endian-ness. The C side will dump the entire struct the way it is in the memory, with all its gaps that the compiler puts in for performance etc. That's "the mother of non-portability"!

Instead, you should use protocol buffers, JSON, or some other mean of portable serialization to accomplish your task.

like image 144
Sergey Kalinichenko Avatar answered Dec 26 '22 10:12

Sergey Kalinichenko


Use a library that serializes your data to disk. That will make reading it back into Java a whole lot easier. Make sure that the library uses a well-documented storage format.

like image 37
nes1983 Avatar answered Dec 26 '22 08:12

nes1983