【问题标题】:Obtain void* pointer to content of boost::any获取指向 boost::any 内容的 void* 指针
【发布时间】:2012-06-28 14:04:14
【问题描述】:

我正在使用一个外部库,它有一个接受 void* 的方法

我希望这个 void* 指向一个包含在 boost::any 对象中的对象。

是否可以获取 boost::any 对象的内容地址?

我正在尝试使用 myAny.content,但到目前为止还没有运气!我希望 dynamic_cast 或 unsafe_any_cast 的某种组合能够满足我的需求。

谢谢!

【问题讨论】:

    标签: c++ boost boost-any


    【解决方案1】:

    您可以使用boost::any_cast 获取指向底层类型的指针(前提是您在编译时知道它)。

    boost::any any_i(5);
    
    int* pi = boost::any_cast<int>(&any_i);
    *pi = 6;
    
    void* vpi = pi;
    

    【讨论】:

    • 这段代码实际上在做什么?看起来它正在将地址本身转换为 int。怎么会这样?
    • boost::any_cast 就是这样做的。它具有与dynamic_cast 相似的语义。在这种情况下,转换为 int* 将成功,因为存储的基础类型是 int。转换为其他指针类型(比如float*)将导致返回nullptr。转换为引用类型要么成功,要么抛出boost::bad_any_cast 异常。 boost::any 仅适用于精确类型匹配,如果我没记错的话,它使用 typeid 进行匹配。
    【解决方案2】:

    很遗憾,这是不可能的;如果类型与包含的类型不同,boost::any_cast 将拒绝强制转换。

    如果您愿意使用不受支持的内部 hack,current version of the header 有一个未记录且不受支持的函数 boost::unsafe_any_cast(顾名思义)绕过 boost::any_cast 执行的类型检查:

    boost::any any_value(value);
    void *content = boost::unsafe_any_cast<void *>(&any_value);
    

    标题有这样的说法unsafe_any_cast

    // Note: The "unsafe" versions of any_cast are not part of the
    // public interface and may be removed at any time. They are
    // required where we know what type is stored in the any and can't
    // use typeid() comparison, e.g., when our types may travel across
    // different shared libraries.
    

    【讨论】:

    • 这应该是文档化接口的一部分,因此boost::any 可以与使用void* 的遗留代码一起使用。最可悲的是,std::experimental::any 似乎连unsafe_any_cast 都没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 2011-06-22
    • 2015-07-02
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多