Search code examples
socketsbufferstdd

Use Structure as Buffer in D


I want to read from a socket, and forward all output to a socket. In C you would simply forward a pointer to the structure, and an integer saying how big your structure is.

In D however, there actually are arrays, and not simply pointers. How do I read from a Socket into a structure in D?

struct MyStruct {
    ubyte myVar;
}

MyStruct myStruct;
socket.receive(myStruct); // How to do this

Solution

  • Generically, you can get a ubyte[] out of any memory by casting it to a pointer, then slicing it:

    ubyte[] buffer = (cast(ubyte*)&myStruct)[0 .. myStruct.sizeof]);
    

    Someone on the chat room a couple days ago showed an even shorted way to do it, but I don't remember what it was...

    A D array is a pointer and length pair so conceptually, it is the same as the C pointer and integer.

    BTW for Sockets, don't forget to check the return value because you might not get enough data to fill the whole struct at once! receive returns as soon as it has any data, which on the open network might only be one packet that leaves the the array/struct not completely full.