I have a socket where server is in JAVA but Client is in C++.
Struct{
float length;
char[] name;
}myStruct;
How can I convert the structures to a byte stream sent by Server and can be correctly parsed by Client? Any sample code would help! (I heard XML is an option but I am not familiar with it ) Thanks.
Try using Google's protocol buffers, hosted at the ProtocolBuffers page at Google Code. Small, efficient, python, Java, and C++ support. Sounds like it suits your needs well.
Less overhead than an XML approach, and better than rolling your own - it's harder than you'd think.
XML doesn't do Magic
you can use XML or plain text
to do that think what you whould have done working with files.
you would use jave to write the data to a file
then you can use c++ to read this file.
well the same is with socket
XML isn't special. plain text can do the work
XML only add structure
i wouldn't suggested to implement serialization by yourself for heavy tasks
you may consider using JNI/JNA a better way is to use corba but that may be an overkill
based on @finnw's answer...
class MyStruct {
float length;
String name;
}
void send(SocketChannel dst, MyStruct ms) throws IOException {
int len = 5 + ms.name.length();
ByteBuffer buf = ByteBuffer.allocate(len);
buf.putInt(len);
buf.putFloat(ms.length);
buf.put(ms.name.getBytes("US-ASCII"));
buf.put((byte) 0);
buf.flip();
dst.write(buf);
}
On the C side
struct mystruct *readMyStruct(int fd) {
uint32_t size;
read(fd, &size, sizeof size);
struct mystruct *result = malloc(size);
read(fd, result, size);
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With