<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dooba.net &#187; UDP</title>
	<atom:link href="http://dooba.net/tag/udp/feed/" rel="self" type="application/rss+xml" />
	<link>http://dooba.net</link>
	<description>Tech, Science, Insanity</description>
	<lastBuildDate>Tue, 06 Mar 2012 05:30:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>C# and Serializing Structs to byte arrays</title>
		<link>http://dooba.net/2009/07/02/c-sharp-and-serializing-byte-arrays/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=c-sharp-and-serializing-byte-arrays</link>
		<comments>http://dooba.net/2009/07/02/c-sharp-and-serializing-byte-arrays/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 19:54:46 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[C-Sharp]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[UDP]]></category>

		<guid isPermaLink="false">http://dooba.net/?p=166</guid>
		<description><![CDATA[So I have a application in C# that is communicating to something else via UDP messages. The messages are byte packed arrays of data. There are several bytes of header and then N bytes of data whos format is described in the header. I might send several Ints, or a string, or whatever. This is [...]]]></description>
			<content:encoded><![CDATA[<p>So I have a application in C# that is communicating to something else via UDP messages. The messages are byte packed arrays of data. There are several bytes of header and then N bytes of data whos format is described in the header. I might send several Ints, or a string, or whatever.</p>
<p>This is pretty easy to handle in C/C++ as you can get raw pointers to everything. So if each message type is a struct, I can get a char* to the address of the struct and just read N bytes and send that out.</p>
<p>The problem on the C# end is this isnt so easy. If I want to pull messages apart and put them back into structs I have to do this manually each multi byte field at a time. So I was left with a function call for each message type to serialize it, and then another to deserialize it, each one having to know exactly what was in each message, so if I changed a message I&#8217;d have to edit all the handling functions. What I needed was a way to jsut get the raw bytes the in the received array into a struct of the right type, and vice versa. Fortunately there are some tricky ways to make this super easy.</p>
<p>First, we have to make sure the structs we declare in C# and packed. Here is an example:</p>
<pre name="code" class="c#">
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack=1)]
struct msg1{
     int a;
     int b
     short c;
}
</pre>
<p>This will ensure there are no gaps between elements in the struct.</p>
<p>Next, we need a way to take an array of Bytes and copy it directly into the struct:</p>
<pre name="code" class="c#">
public static T DeserializeMsg< T >(Byte[] data) where T : struct
        {
            int objsize = Marshal.SizeOf(typeof(T));
            IntPtr buff = Marshal.AllocHGlobal(objsize);

            Marshal.Copy(data, 0, buff, objsize);

            T retStruct = (T)Marshal.PtrToStructure(buff, typeof(T));

            Marshal.FreeHGlobal(buff);

            return retStruct;
        }
</pre>
<p>Lets say we have a msg1 struct populated and we want to send that out over UDP. We need to serialize it back to raw bytes. This function will do just that:</p>
<pre name="code" class="c#">
public static Byte[] SerializeMessage< T >(T msg) where T : struct
        {
            int objsize = Marshal.SizeOf(typeof(T));
            Byte[] ret = new Byte[objsize];

            IntPtr buff = Marshal.AllocHGlobal(objsize);

            Marshal.StructureToPtr(msg, buff, true);

            Marshal.Copy(buff, ret, 0, objsize);

            Marshal.FreeHGlobal(buff);

            return ret;
        }</pre>
<p>Thats it!</p>
<p><img src="http://www.beqrious.com/generate_image.php?type=http://&#038;text=http://dooba.net/2009/07/c-sharp-and-se…ng-byte-arrays/" alt="qrcode"  /></p>
]]></content:encoded>
			<wfw:commentRss>http://dooba.net/2009/07/02/c-sharp-and-serializing-byte-arrays/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->
