gpt4 book ai didi

c++ - 表示命令包格式的数据结构

转载 作者:行者123 更新时间:2023-12-01 14:50:18 24 4
gpt4 key购买 nike

我的目的是建立一个配置文件。因此,我基本上必须以某种方式表示命令包结构。

当实际数据(二进制)到来时,我想将数据包与此配置文件进行比较,然后对其进行处理(将数据转换为CSV格式)。

因此,有不同的命令类型。

因此,每次出现数据包时,我都必须获取其操作码,并使用配置文件对其进行检查,然后返回代表该数据包格式的适当命令格式。

命令格式如下所示:

操作码-1个字节-整数

命令-4字节-字符串

...

所有命令都没有相同数量的字段或相同的格式。

我想检索所有这些详细信息。我可以用XML表示它,并使用诸如libxml2之类的库对其进行解析。

以下是示例XML格式:

 <cmd type="Multiplication">
<field name="opcode" type="string" bytes="4"/>
<field name="Multiplicand" type="number" bytes="2"/>
<field name="Multiplier" type="number" bytes="2"/>
</cmd>

但是这种方法相当慢。

我的想法是以某种方式在结构中表示命令包格式。但是,由于C / C++不是反射语言,因此无法知道结构成员,并且每个结构(命令)都需要一个函数来解析它。

请提出一种存储格式的方法,以使一个泛型函数仅通过查看这种格式就可以解析二进制数据。
  • 语言可以是C或C++。
  • 性能是最高优先级,因此不鼓励使用XML和类似类型。
  • 在内存中首选数据结构。

  • 非常感谢您的帮助。

    最佳答案

    我认为您最好的选择是将文件表示为正确命令类型的variant的集合。例如,假设您有三个命令选项:

    struct Constant {
    short value;
    };
    struct UnaryOperation {
    unsigned char opcode;
    short value;
    };
    struct BinaryOperation {
    unsigned char opcode;
    short value1;
    short value2;
    };

    代表未知命令。 如果您有未知命令,则可以将其表示为三种类型的 variant:
    using Command = std::variant<Constant, UnaryOperation, BinaryOperation>; 

    根据命令类型应用功能。 假设每个命令具有不同的功能:
    short eval(Constant c) {
    return c.value;
    }
    short eval(UnaryOperation u) {
    switch(u.opcode) {
    // stuff
    }
    }
    short eval(BinaryOperation b) {
    switch(b.opcode) {
    // stuff
    }
    }

    我们可以使用 std::visit来评估任意 Command:
    short evaluate_command(Command const& command) {
    short output;
    // This calls the right overload automatically
    std::visit(command, [&](auto cmd) { output = eval(cmd); });
    return output;
    }

    解析命令。
    我们可以根据定义的任何类型自动创建 std::variant。这意味着,如果您提供一种方法来确定基于文件的命令,则很容易做到。
    enum class OpType : unsigned char {
    ConstantOp, UnaryOp, BinaryOp
    };
    // Command can be automatically constructed from a Constant, a UnaryOperation, or a BinaryOperation
    Command readFromStream(std::istream& i) {
    OpType type;
    unsigned char op;
    short value, value2;

    // Read the type of the operation
    i >> (unsigned char&)type;

    //Return either a Constant, a UnaryOperation, or a BinaryOperation
    switch(type) {
    case OpType::ConstantOp: {
    i >> value;
    return Constant{value};
    }
    case OpType::UnaryOp: {
    i >> op >> value;
    return UnaryOperation{op, value};
    }
    case OpType::BinaryOp {
    i >> op >> value >> value2;
    return BinaryOperation{op, value, value2};
    }
    }
    }

    关于c++ - 表示命令包格式的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56100825/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com