Silverlight 编程 之 如何绕过unsafe mode

来源:互联网 发布:林黛玉美图 知乎 编辑:程序博客网 时间:2024/05/16 12:47

 

虽然同为C#语言,但Silverlight不支持unsafe mode下的编程,下面将针对具体问题介绍一些替代方法。

 

 

我们经常会用到

unsafe
{
//Marshal.Copy(frame.packet, 0, (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();
 

 

 下面给大家推荐一些好的帖子供进一步学习:

http://stackoverflow.com/questions/2079868/marshal-ptrtostructure-throwing-system-argumentexception-error