jeudi 12 janvier 2017

Unique structs in child classes (C#)

I am developing an app that generates binary blobs from its input. As there are many types binary blob, I want to define a parent class called Config, and then multiple child classes. The parent class will have a method that generates the binary blob, with each child class having a unique struct that defines the format of the blob.

Parent:

class Config
{
    public struct BinaryFormat
    {
        public UInt16 _config_length;
    }

    // compile parameters to binary format
    public byte[] CompileToBinary()
    {
        // find the binary format struct
        ??????

        foreach (var field in typeof(BinaryFormat).GetFields(BindingFlags.Instance | BindingFlags.Public))
        {
            string identifier = field.Name;
            if (identifier == "_config_length")
                continue;
            ConfigParameter param = FindParameterByIdentifier(identifier);
            if (param == null)
                throw new Exception("Struct field with no matching parameter (" + identifier + ")");
            field.SetValue(null, param.value);
        }

        int size = Marshal.SizeOf(cfg);
        cfg._config_length = (UInt16)size;
        byte[] buffer = new byte[size];
        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(cfg, ptr, true);
        Marshal.Copy(ptr, buffer, 0, size);
        Marshal.FreeHGlobal(ptr);

        return buffer;
    }
}

Child:

class ChildConfig : Config
{
    [StructLayout(LayoutKind.Sequential)]
    public struct BinaryFormat
    {
        public UInt16 _config_length;

        public sbyte config1;
        public sbyte config2;
        public sbyte config3;
    }
}

In CompileToBinary() if I just create a new variable of type BinaryFormat it uses the struct from the parent class. How can I use the struct from the child class?

Or is this entirely the wrong way to go about this?





Aucun commentaire:

Enregistrer un commentaire