Sending a struct over TCP
BCS
ao at pathlink.com
Tue Mar 6 14:31:14 PST 2007
Reply to SirErugor,
> Hi there,
>
> I've set up a server and a client application and I want to be able to
> send a struct with fx. an integer and a char[]. So first I convert it
> to a ubyte[] like this:
>
> ..
> void write(T)(T input)
> {
> buf ~= *(cast(ubyte[T.sizeof]*)&input)[0 .. T.sizeof];
> }
> Then I send the ubyte[] over through TCP via a SocketStream. On the
> client-side I read and convert the ubyte[] back to the struct:
>
> uint len = ss.read(buffer);
> auto mem = new mem_stream(buffer[0 .. len]);
> data d = mem.read!(data);
> writefln("[id:%d] len=%d, data=%s (%d)", d.id, len, d.content,
> d.content.sizeof);
> Which outputs: [id:100] len=12, data= (8)
>
> The read function:
> ..
> int pos = 0;
> ..
> T read(T)()
> {
> T output = *(cast(T*)(buf[pos .. pos + T.sizeof].ptr));
> pos += T.sizeof;
> return output;
> }
> The Integer got sent perfectly (and i does the same with additional
> ulongs etc.) but the char[] did not, though, it is still the same
> size.
>
> So why can't I send the char[]? is it because it is a array of
> pointers to the address-space of the server?
>
> Thank you in advance :)
>
> (Btw. My files are also attatched)
>
char[] is by reference. under the hood it is a pointer/length pair.
Somewhere I have a code generator that tries to make this work.
More information about the Digitalmars-d-learn
mailing list