[英]Obtain void* pointer to content of boost::any
I am using an external library that has a method which accepts a void* 我正在使用一个外部库,它有一个接受void *的方法
I want this void* to point to an object contained within a boost::any object. 我希望这个void *指向boost :: any对象中包含的对象。
Is it possible to get at the address of the content of a boost::any object? 是否有可能获得boost :: any对象的内容地址?
I'm trying to play with myAny.content but no luck so far! 我正在尝试使用myAny.content,但到目前为止还没有运气! I'm hoping some combination of dynamic_cast or unsafe_any_cast will give me what I need.
我希望dynamic_cast或unsafe_any_cast的某些组合能够满足我的需求。
Thanks! 谢谢!
You can use boost::any_cast
to get a pointer to the underlying type (provided you know it at compile time). 您可以使用
boost::any_cast
来获取指向底层类型的指针(前提是您在编译时知道它)。
boost::any any_i(5);
int* pi = boost::any_cast<int>(&any_i);
*pi = 6;
void* vpi = pi;
This isn't possible, unfortunately; 不幸的是,这是不可能的;
boost::any_cast
will refuse the cast if the type is distinct from the contained type. 如果类型与包含的类型不同,
boost::any_cast
将拒绝boost::any_cast
。
If you're willing to use an unsupported internal hack, the current version of the header has an undocumented and unsupported function boost::unsafe_any_cast
which (as its name suggests) bypasses the type check performed by boost::any_cast
: 如果您愿意使用不受支持的内部hack,则当前版本的头文件具有未记录且不受支持的函数
boost::unsafe_any_cast
(顾名思义)绕过boost::any_cast
执行的类型检查:
boost::any any_value(value);
void *content = boost::unsafe_any_cast<void *>(&any_value);
The header has this to say about unsafe_any_cast
: 标题有关于
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.