1 回答
TA贡献1831条经验 获得超4个赞
这将工作,没有不安全的代码(但实际上它仍然很不安全)...... try... finally...with emptytry {}用于防止异步异常。
public struct OrderStruct
{
public const int SIZE = 16;
public int AssetId;
public int OrderQty;
public double Price;
public static OrderStruct FromBytes(byte[] data)
{
if (data.Length < SIZE)
throw new ArgumentException("Size is incorrect");
GCHandle h = default(GCHandle);
try
{
try
{
}
finally
{
h = GCHandle.Alloc(data, GCHandleType.Pinned);
}
OrderStruct t = Marshal.PtrToStructure<OrderStruct>(h.AddrOfPinnedObject());
return t;
}
finally
{
if (h.IsAllocated)
{
h.Free();
}
}
}
public byte[] ToBytes()
{
var result = new byte[SIZE];
GCHandle h = default(GCHandle);
try
{
try
{
}
finally
{
h = GCHandle.Alloc(result, GCHandleType.Pinned);
}
Marshal.StructureToPtr(this, h.AddrOfPinnedObject(), false);
return result;
}
finally
{
if (h.IsAllocated)
{
h.Free();
}
}
}
}
- 1 回答
- 0 关注
- 170 浏览
添加回答
举报