简体   繁体   English

在C#中更改结构以匹配新的C定义

[英]Change struct in C# to match new C definition

I'm developing a program using C# + WPF for analyzing a firmware of a embedded system. 我正在使用C#+ WPF开发一个程序,用于分析嵌入式系统的固件。 This firmware is written in C and includes many structs. 该固件用C语言编写,并包含许多结构。 One of these structs has been changed following new firmware version. 在新的固件版本之后,这些结构之一已更改。 My software has to support all firmware versions. 我的软件必须支持所有固件版本。

Firmware ver.1 固件版本1

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MainStruct
{
    public byte Member1;
    public byte Member2;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
    public UInt16[] Member3;
}

Firmware Ver.2 固件Ver.2

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MainStruct
{
    public byte Member1;
    public Uint Member2;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    public UInt16[] Member3;
}

Logic 逻辑

public void ShowStruct(MainStruct MyStruct)
{
    ShowData(MyStruct.Member3);
}

Outline of steps the software performs: 该软件执行的步骤概述:

  1. Access device 存取装置
  2. Get firmware version 获取固件版本
  3. Select Struct 选择结构

How to ensure compatibility? 如何保证兼容性?

Make both versions of your struct implement an interface. 使两个版本的结构都实现一个接口。 Make your interface have the getters and setters for each object. 使您的界面具有每个对象的getter和setter。 Make sure you handle casting correctly. 确保正确处理铸造。

interface MainStructInterface()
{
    void setMember1(byte b);
    byte getMember1();
    void setMember2(Uint b); // Cast to byte in the first firmware version struct.
    Uint getMember2();
    // etc
}

Also, check out this struct layout formatting: 另外,请查看此结构布局格式:

    [StructLayout(LayoutKind.Explicit, Pack = 1)]
    public unsafe struct StructMessage
    {
        [FieldOffset(0)] public fixed byte data[13]
        [FieldOffset(0)] public byte Member1;
        [FieldOffset(1)] public Uint Member2;
        [FieldOffset(5)] public fixed UInt16 Member3[4];
    }

Using that format you can load everything into the byte array and then access each member very easily. 使用这种格式,您可以将所有内容加载到字节数组中,然后非常轻松地访问每个成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM