1

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.

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.