Scott Chamberlain
Scott Chamberlain

Reputation: 127543

Convert a struct to an object array

I am reading in a binary file in to a struct with StructLayout(LayoutKind.Explicit) set. I need to move this data in to a DAO which has the structure of Object[]. Instead of manually typing each of the 40 or so fields that are in the struct I would just like to use reflection and convert all of the elements not starting with "Unknown". Here is what I have so far.

[StructLayout(LayoutKind.Explicit, CharSet=CharSet.Ansi)]
struct ClientOld : IStuctToArray
{
    [FieldOffset(0)]
    public byte Active;

    [FieldOffset(1)]
    [MarshalAs(UnmanagedType.AnsiBStr)]
    public string Title;

    [FieldOffset(10)]
    [MarshalAs(UnmanagedType.AnsiBStr)]
    public string LastName;

    [FieldOffset(36)]
    [MarshalAs(UnmanagedType.LPArray, SizeConst = 2)]
    public byte[] Unknown1;

    (...)

    [FieldOffset(368)]
    [MarshalAs(UnmanagedType.AnsiBStr)]
    public string AddedBy;

    [FieldOffset(372)]
    [MarshalAs(UnmanagedType.LPArray, SizeConst = 22)]
    public byte[] Unknown7;

    public object[] ToObjectArray()
    {
        return this.GetType().GetFields()
                   .Where(a => !a.Name.StartsWith("Unknown"))
                   .Select(b => /* This is where I am stuck */)
                   .ToArray();
    }
}

I do not know what to put in the select area to get the value of my field. b.GetValue requires you to pass in a object and I do not know what object to pass.

Any help would be greatly appreciated.

Upvotes: 1

Views: 1491

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292405

Use the GetValue method and pass the object for which you need the value, i.e. this:

    return this.GetType().GetFields()
               .Where(f => !f.Name.StartsWith("Unknown"))
               .Select(f => f.GetValue(this))
               .ToArray();

Upvotes: 3

Related Questions