Reputation: 979
I have a very specific requirement. I have a java application, where I have to convert byte array in to message having java types like int, String. The structure of the message is defined in c++ as below -
struct SMSMessage{
int id;
std::string name;
std::string source;
std::string destination;
std::string timestamp;
int type;
int status;
std::string message;
int mesg_type;
int mesg_sub_type; };
What I receive in my java application is the byte array. I don't know wheather c++ application is using proto buffers or any other way to convert in to a byte array. But, if I parse the array using byte by byte, I could get the values. For example -
ByteBuffer.wrap(Arrays.copyOfRange(byteArray, 0, 4)).getInt();
//byteArray -- reference to the incoming byte array
// 0, 4-- range of bytes for integer type
This line will return correct id value (First property in structure is int).
My question are - If I write the proto for this structure, could I be able to parse this message in to java ?
Is there any other way to convert the byte array to java types ?(not using library like google protobuf )
Upvotes: 0
Views: 844
Reputation: 489
You may be able to use the open source javolution library specifically take a look at the Struct class which provides some support for directly mapping C structs to Java types.
You will encounter problems mapping the std::string type as the length of the string is not known beforehand. You will need to read this in as a byte stream until you find the null terminator which signifies the end of a string.
Upvotes: 0
Reputation: 134
I'am not sure if you can convert it directly into a java structure but i guess it is not so easy possible. Also if it works you can't be sure that the size of the Datatypes are the same. If you run the C++ Application and the Java Application on a different Machine with a different architecture it can be different sizes.
So in my opinion the best option would be you write it first into a json or xml file and read it back from the other application.
If you want do it like you already wrote, then maybe you should sort the c++ struct by types. So you can better use a loop. Like, i have 5 times a integer of 4 bytes and 5 times a string with X Bytes.
mfg
Upvotes: 1