0

I'm currently working with a struct which is written into a buffer. When reading the struct back into my Application i get the following exception:

Unable to cast object of type 'System.Windows.Documents.TextStore' to type 'System.Version'.

Code

The exception is thrown when casting the result back ( (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); ).

protected static T ReadStruct<T>(Stream input)
    where T : struct
{
    Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))];
    input.Read(buffer, 0, buffer.Length);
    GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
    T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    handle.Free();
    return result;
}

Used data-structure

/// <summary>
/// The header for all binary files
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet=CharSet.Ansi)]
public unsafe struct BinaryHeader
{
    public const String MAGIC_KEY = "TABF";

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
    String _Magic;
    Version _Version;
    DateTime _Timestamp;
    Guid _Format;
    Int64 _Reserved0;
    Int64 _Reserved1;
    /// <summary>
    /// The magic value for the test automation binary
    /// </summary>
    public String Magic
    {
        get
        {
            return _Magic;
        }
    }
    /// <summary>
    /// The version of the assembly ( used for debugging )
    /// </summary>
    public Version AssemblyVersion { get { return _Version; } }
    /// <summary>
    /// The formatGuid of the current binary
    /// </summary>
    public Guid FormatGuid { get { return _Format; } }
    /// <summary>
    /// The timestamp of the file
    /// </summary>
    public DateTime Timestamp { get { return _Timestamp; } }

    public BinaryHeader(Guid formatGuid)
    {
        _Reserved0 = 0;
        _Reserved1 = 0;

        _Version = BinaryBase.AssemblyVersion;
        _Format = formatGuid;
        _Timestamp = DateTime.Now;
        _Magic = MAGIC_KEY;
    }
}
4

1 回答 1

2

用这种方法编写自己的二进制序列化方案是可以的,但您必须了解其局限性。一个核心是它只能处理 blittable 值,简单的值类型值。pinvoke marshaller 为具有 [MarshalAs] 属性的字符串提供了一种解决方法。Version类没有这样的解决方法。存储在结构中的指针值将被写入文件。当你回读它时,更正常的事故是你会得到一个 AccessViolationException。除非你有幸指针碰巧取消引用存储在 GC 堆上的有效对象。在您的情况下为 TextStore 类型的对象。

当然,这并不完全是幸运。您必须重新考虑您的方法,_Version 字段必须删除。不要犹豫使用 BinaryFormatter 类,这正是它要做的。

于 2012-04-18T14:27:36.053 回答