Unsafe code is an undocumented feature of NETMF, and only works for a limited set of operations. I have never been successful in using pointers as the target of an assignment operation; however, you can use unsafe operations to perform unsupported type-casts.
Copying an integer type (e.g. short) into a byte array can be done with the for-loop method and bit shift operations or just two assignment operations.
You would need unsafe code to push floating point numbers into a byte array, however, since there is no overload method for the bit shifters for floats.
Example code that works:
public unsafe class MyConverter
{
// This is a safe method
public static void getBytes(byte[] buf, short n)
{
for(int i = 0; i<sizeof(short); i++)
{
buf[i] = (byte)(n & 0xFF);
n = (short) (n >> 8);
}
}
// This is also a safe method
public static void getBytes(byte[] buf, uint n)
{
for (int i = 0; i < sizeof(uint); i++)
{
buf[i] = (byte)(n & 0xFF);
n = (n >> 8);
}
}
// This one is not safe
public unsafe static void getBytes(byte[] buf, float n)
{
// cannot pass dereferenced pointer directly to overload
// must assign it to a local variable
uint val = *((uint*)&n);
getBytes(buf, val);
}
}
The only reason I have ever used them is to send data packets over serial or TCP/IP which require converting some value type into an array of bytes. According to the documentation, [em]Microsoft.SPOT.Reflection[/em] namespace provides [em]Serialize[/em] and [em]Deserialize[/em] methods to do this, however, in one test, I could not get them to work.
The NETMF is missing several of the other common approaches to this such as the BitConverter class, and the BinaryReader and BinaryWriter classes.
@ nicholas.goodman - I had same problem month ago and serialize/deserialize are not compatible in any case with .NET fwk. I switched to XMLSerializer that can serialize/deserialize classes to/from .NET. That can be helpful as a starting point. Search in codeshare published by JREndean, here it is: