【问题标题】:Change attribute type when parsing binary with boost::spirit使用 boost::spirit 解析二进制文件时更改属性类型
【发布时间】:2012-03-31 16:42:32
【问题描述】:

我已经成功地使用boost::spirit::qi 来解析由内置解析器(例如byte_、little_word 等)组成的流。但是,我现在需要解析不完全属于这些类别之一的数据。比如我想把一个16.16的定点二进制数转换成double;例如所以little_word << little_16p16 会解析uint16_t,后跟double(从定点数解析)。

我首先考虑了语义动作,但是(我认为...)它们不合适,因为它们不会更改与解析器关联的属性的类型。我也无法弄清楚如何使employee struct-parsing example 适应这种情况,因为它依赖于boost::fusion 提供的隐式转换。这种方法在这里行不通,因为我显然无法定义从 uint32_t 到 double 的隐式转换而不引起重大问题。

我的倾向是我需要添加非终端来包装内置的二进制原始解析器或从头开始编写终端解析器。即使查看了qi_binary.hpp 的来源,我也不知道该怎么做。谁能提供一些示例代码和/或指导我参考相关参考资料以开始使用?

【问题讨论】:

    标签: c++ parsing binary boost-spirit boost-spirit-qi


    【解决方案1】:
        template < typename Iterator >
        struct parser : boost::spirit::qi::grammar < Iterator, double(), boost::spirit::ascii::space_type >
        {
            struct cast_impl
            {
                template < typename A >
                struct result { typedef double type; };
    
                double operator()(boost::fusion::vector < boost::uint16_t, boost::uint16_t > arg) const
                {
                    // cast here
                    return 0;
                }
            };
    
            parser() : parser::base_type(main)
            {
                pair = boost::spirit::qi::little_word >> '.' >> boost::spirit::qi::little_word;
                main = pair[boost::spirit::qi::_val = cast(boost::spirit::qi::_1)];
            }
    
            boost::spirit::qi::rule < Iterator, boost::fusion::vector < boost::uint16_t, boost::uint16_t > (), boost::spirit::ascii::space_type > pair;
            boost::spirit::qi::rule < Iterator, double(), boost::spirit::ascii::space_type > main;
    
            boost::phoenix::function<cast_impl> cast;
        };
    
        int _tmain(int argc, _TCHAR* argv[])
        {
            typedef std::string container;
    
            container data_ = "\x01\x02.\x01\x02";
    
            container::iterator iterator_ = data_.begin();
    
            double value_;
    
            bool result_ =
                boost::spirit::qi::phrase_parse(iterator_, data_.end(),
                parser < container::iterator > (),
                boost::spirit::ascii::space,
                value_);
    
            return 0;
        }
    

    【讨论】:

    • 谢谢!通过删除 ascii::space_type 模板参数并替换为适当的 operator() 函数,我能够让您的示例代码完全按照我的意愿行事。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多