0

I have a C program with the following structs defined:

typedef struct{
   DWORD id;
   char  name[256];
}ROW;


typedef struct{
   DWORD        Prev;
   DWORD        Next;
   WORD         ItemCount;
   struct  ROW  Item[256];
} PAGE;

...at some point the program fills the PAGE struct and writes it to a disk file.

Now, I need to read this file from a C# program, but I can't figure out how to define an equivalent class in C#, everything I've tried either fails to compile or throws an exception. In C this is a very trivial task and very probably in C# it is too, however I am new to C# and haven't found yet a clear explanation about how to do it properly.

3
  • Do you know whether the structs are packed or aligned. If aligned then there is two bytes of padding between ItemCount and Item. I also suspect that what is stored to the file will not necessarily contain all 256 ROW items. I guess it will contain only ItemCount of them. I'd say you need to choose between Marshal.PtrToStructure and BinaryReader. Which do you prefer? Do you know the answers to any of these questions? Commented Feb 12, 2014 at 15:16
  • Structs are packed, the compiler was setup to use 1 byte struct alignment... the files does contain all the 256 rows whether used or not. I'm using BinaryReader haven't tried yet Marshal.PtrToStruct... you are the expert, which is the most appropriated for this situation?
    – george b
    Commented Feb 12, 2014 at 15:25
  • I think I'd use BinaryReader here. The reason being PtrToStructure involves creating struct types that are only useful when reading the file. In your C# code you'll likely want a Row struct and a Page class that contains a List<Row>. Would you like me to show you some outline code on that basis? Commented Feb 12, 2014 at 15:29

3 Answers 3

1

Personally I'd use BinaryReader here. The reason being that it allows you to define one set of types to represent these structures, that feels clean in C#. If you were to use Marshal.PtrToStructure then you are compelled to define interop types that feel clunky in C#.

You state that the structs are packed which is good. Aligned structures makes life harder because you have to understand how the compiler laid out the structures. For storing to disk, aligned structures should generally be avoided.

I would perhaps define types like this:

public struct Row
{
    public uint id;
    public string name;
}

public struct Page
{
    public uint prev;
    public uint next;
    public Row[] items;
}

You could use classes if you prefer. Or List<Row>. It's really up to you.

Then read the file with a method like this:

public static Page ReadPage(BinaryReader reader)
{
    Page page;
    page.prev = reader.ReadUInt32();
    page.next = reader.ReadUInt32();
    ushort count = reader.ReadUInt16();
    page.items = new Row[count];
    for (int i=0; i<count; i++)
    {
        page.items[i].id = reader.ReadUInt32();
        page.items[i].name = Encoding.ASCII.GetString(reader.ReadBytes(256));
    }
    // skip past the unused rows
    reader.ReadBytes((256+sizeof(uint))*(256-count)); 
}

I've assumed ASCII encoding. But perhaps it is UTF-8 or ANSI. I assume that the strings are null-terminated, but have not actually coded any null-terminator detection. I'm hoping you'll be able to do that!

3
  • You code is nice and clean, and for what I've researched it seems like this is the most natural way to do it in C#, however used to think as a C programmer as I am, wouldn't this approach lead to severe performance issues??? I would need to perform any number between 5 and 515 reads per chunk of data... and there is a lot in that file.
    – george b
    Commented Feb 12, 2014 at 17:20
  • @georgeb The .net framework is well designed in this regard. No you do not want to issue lots of I/O instructions for 4 bytes at a time. But that is solved by buffering, done outside BinaryReader. For instance, you would be using a FileStream to read from a file. When you create the file stream object, specify a suitable buffer size. This separation of concerns if very desirable. You don't want to be worrying about buffering when decoding a structured file. That's a separate concern. Commented Feb 12, 2014 at 17:26
  • Thanks, you answer seems to be the best... I'll work based on it and let you know what happens.
    – george b
    Commented Feb 12, 2014 at 17:48
0

Note that this is risky in C -- you can't guarantee the struct won't be padded with additional bytes. (Well, not without some compiler-specific flags.)

The StructLayout attribute lets you define how your struct is laid out:

[StructLayout(LayoutKind.Sequential)]
public struct Point 
{
   public int x;
   public int y;
}   

This will put x and then y. If you want to force byte alignment, you can do:

[StructLayout(LayoutKind.Sequential,Pack=1)]
public struct Point 
{
   public int x;
   public int y;
}   

(which doesn't matter in this case, but with other items it might). You can also define exact layouts of every field:

[StructLayout(LayoutKind.Explicit)]
public struct Rect 
{
   [FieldOffset(0)] public int left;
   [FieldOffset(4)] public int top;
   [FieldOffset(8)] public int right;
   [FieldOffset(12)] public int bottom;
} 

(examples lifted from MSDN: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute%28v=vs.110%29.aspx)

You should be able to then use Marshal.PtrToStructure to read in the raw bytes and overlay the structure on top of it. I don't have example code handy (been a few years since I've done it), but it does work.

0

You have to use the [StructLayout-Attribute] (http://msdn.microsoft.com/de-de/library/system.runtime.interopservices.structlayoutattribute%28v=vs.110%29.aspx) e.g.:

[StructLayout(LayoutKind.Sequential, Pack = ?, Size = ??)]
public struct SomeStruct 
{
  public ushort wYear; 
  public ushort second;
  public ushort third; 
  ...

}

Someday I've made a generic static method to read a stream into a struct:

 public static T StreamToStruct<T>(Stream stream, int offset = 0) where T : struct
    {
        Type structType = typeof(T);
        if(structType.StructLayoutAttribute.Value != LayoutKind.Sequential)
        {
            throw new ArgumentException("structType isn't a struct or the layout isn't sequential.");
        } 

        int tmpSize = Marshal.SizeOf(structType);

        Byte[] tmp = new Byte[tmpSize];
        stream.Read(tmp, offset, tmpSize);

        GCHandle structHandle = GCHandle.Alloc(tmp, GCHandleType.Pinned);
        try
        {
            T structure = (T)Marshal.PtrToStructure(structHandle.AddrOfPinnedObject(), structType);
            return structure;
        }
        catch(Exception)
        {
            throw;
        }
        finally
        {
            structHandle.Free();
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.