0

I've got a piece of code in which I use boost::unsafe_any_cast<void*>(&boost::any anyInstance) to obtain the content pointer of a boost::any object. The code is this below:

boost::any staticResult;  //contains a private pointer called content
f(staticResult);          //makes the content pointer a null pointer 
void* voidStaticResult = boost::unsafe_any_cast<void*>(&staticResult);

Unfortunately, debugging, I see that the content pointer in staticResult is NULL (0x00000000) while voidStaticResult is 0x00000004.

(Apparently there's no reason for that. Have you got any ideas?)

EDIT: The function f() calls a dll creating an instance of an object. The instance is pointed by the content pointer of staticResult. I need to pass the pointer to another function, but it seems to me there's no easy way to "cast" boost::any to a pointer to the instantiated class. Any other solution would be great.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
XectX
  • 36
  • 4
  • 3
    You're aware of that `boost::unsafe_any_cast` is not really considered a "public" function? And that it could be removed from Boost at any time without warning? Perhaps if you explain the actual problem you wan to solve, we could help you find a solution that doesn't uses what is really considered private and internal functions? – Some programmer dude Jun 26 '18 at 06:56

1 Answers1

2

Probably unsafe any cast is only valid for non empty any's. It is unsafe and unchecked.

Any is often implemented as a pointer at a block of memory where there is a vtable followed by the object instance. So to get a pointer to the object, you add sizeof(vtable ptr) to the any internal pointer, 4 on your build.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524