views:

617

answers:

6

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.

+2  A: 

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

jojo
+1 for writing response in the form of a Haiku! (Almost)
John Dibling
+7  A: 

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.

jmanning2k
+1 for NOT rolling your own
George
A: 
George
+1  A: 

Use JSONRPC http://www.json.org/

Very easy to generate, very easy to parse. There are out of the box libs on the homepage.

Notinlist
Example: `{ "length": 3.45, "name": "John Doe", "favorite_numers": [2,3,5,7,11] }`
Notinlist
+1  A: 

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;
}
Peter Lawrey
I would make sure to use htons() to send my data on the wire in network byte order. And use ntohs() to read network byte order data and convert it into a host representation.
feroze
htons converts unsigned short, perhaps you could explain how this helps.
Peter Lawrey
A: 

The following article describes how to send a structure from java to .NET. You can take the techniques there and modify them. All you need to do is write the deserializer in C.

http://ferozedaud.blogspot.com/2009/11/how-to-send-object-from-java-to-net.html

feroze