Search code examples
network-programmingpointersglibvalagio

Writing a number of bytes to a GLib.OutputStream in Vala


I'm currently writing an application using Vala that requires me to send data over a network. To aid in creating the packets (and updating the protocol at later dates), I have created structures that I am passing to a method as void*. These structures represent how the packet is arranged and allow me to very easily generate a packet to send without having to mess around too much. The problem with this, however, is that the Vala wrapper for GLib.OutputStream.write() doesn't accept a count (even though the original method does). Vala takes the size of the uint8[] passed to it and provides that to the original method. Is there a simple way of getting around this, sans editing the GIO vapi? Possibly a very cheap way of casting a void* to a uint8[] while supplying a size? I'm aiming for very high performance here as the application will be required to maintain thousands of connections simultaneously. Thanks in advance for any help.

~ Michael


Solution

  • I've been using a macro like this:

    #define OBJECT_TO_BUFFER(val,type,size) (*(size) = sizeof(type), (guint8*)val)
    

    To get around this problem. It takes your object and simply returns the same memory as an uint8[]. It has the corresponding prototype in Vala:

    unowned uint8[] Buffer.of<T>(ref T @value);
    

    The header files and VAPI file called “tricks” are in my GitHub. There are similar versions for dealing with arrays of objects.