none
reading c++ structs from a file RRS feed

  • Question

  • Hi all,

    Here is the issue:
    I've got a file that contains c++ structs written to a file, in binary.

    I've got the old code, so I know the what the structs look like.

    Now I've got to read all those structs in c#.
    Any ideas?
    Thanks.

    qin__23
    Monday, September 22, 2008 3:37 PM

Answers

  • You can use the P/Invoker marshaller to convert these binary structures into managed structures.  Declare the structures in your managed code with the [StructLayout] and [MarshalAs] attributes.  That allows you to use Marshal.SizeOf() to determine the size of the structures in the file.  Use FileStream.Read() to read one structure into a properly sized byte[].  Use GCHandle.Alloc() and GCHandle.AddrOfPinnedObject() to get an IntPtr to the byte array, then Marshal.PtrToStructure to convert the byte[] to a managed structure.  GCHandle.Free() to release the pin. 

    Alternatively, you can read the structure into unmanaged memory allocated with Marshal.AllocHGlobal() and P/Invoking CreateFile() and ReadFile(), Marshal.PtrToStructure() to convert, Marshal.FreeHGlobal() to release the buffer.

    Lots of subtle ways to get it wrong but it should be easy to debug.  Good luck.

    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Friday, September 26, 2008 9:57 AM
    Monday, September 22, 2008 8:46 PM
    Moderator