虽然同为C#语言,但Silverlight不支持unsafe mode下的编程,下面将针对具体问题介绍一些替代方法。
我们经常会用到
unsafe
{
//Marshal.copy(frame.packet,(IntPtr)(&pattern),sizeof(PatternModel));
}
由于不支持unsafe mode,所以我们可以通过如下方式解决:
static void Main(string[] args)
{
double d = 3.14159d;
byte[] b = ToByteArray(d);
Console.WriteLine(b.Length);
Console.ReadLine();
double n = FrpmByteArray(b);
Console.WriteLine(n.ToString());
Console.ReadLine();
}
public static byte[] ToByteArray(object anything)
{
int structsize = Marshal.SizeOf(anything);
IntPtr buffer = Marshal.AllocHGlobal(structsize);
Marshal.StructuretoPtr(anything, buffer, false);
byte[] streamdatas = new byte[structsize];
Marshal.copy(buffer, streamdatas, 0, structsize);
Marshal.FreeHGlobal(buffer);
return streamdatas;
}
public static double FromByteArray(byte[] b)
{
GCHandle handle = GCHandle.Alloc(b, GCHandleType.Pinned);
double d = (double)Marshal.PtrToStructure(
handle.AddrOfPinnedobject(),
typeof(double));
handle.Free();
return d;
}
通常针对特殊的数据类型如structure / class data,常常编译会报错
The structureType parameter layout is not sequential or explicit
针对类定义可以仿照如下方式定义
[StructLayout(LayoutKind.Sequential)]
public class AnyName{ ... }
或者将类定义为struct
public struct AnyName{ ... }
此外针对特殊的类型如enum,可以仿照下面的方式处理
// byte 2 structure
GCHandle handle = GCHandle.Alloc(frame.packet,GCHandleType.Pinned);
Type type = typeof (PatternModel);
pattern = (PatternModel)Marshal.PtrToStructure(
handle.AddrOfPinnedobject(),
Enum.GetUnderlyingType(typeof(PatternModel)));
handle.Free();
下面给大家推荐一些好的帖子供进一步学习: