获取 void* 指向 boost::any 内容的指针

Obtain void* pointer to content of boost::any

本文关键字:指针 any 获取 指向 boost void      更新时间:2023-10-16

我正在使用一个外部库,该库具有接受 void

* 的方法*

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

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

我正在尝试玩myAny.content,但到目前为止没有运气!我希望dynamic_cast或unsafe_any_cast的某种组合能给我所需要的。

谢谢!

您可以使用

boost::any_cast获取指向基础类型的指针(前提是您在编译时知道它)。

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

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

如果您愿意使用不受支持的内部黑客,则当前版本的标头具有未记录且不受支持的函数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.