Obtain void* pointer to content of boost::any - c++

I am using an external library that has a method which accepts a void*
I want this void* to point to an object contained within a boost::any object.
Is it possible to get at the address of the content of a boost::any object?
I'm trying to play with myAny.content but no luck so far! I'm hoping some combination of dynamic_cast or unsafe_any_cast will give me what I need.
Thanks!

You can use boost::any_cast to get a pointer to the underlying type (provided you know it at compile time).
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.
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:
boost::any any_value(value);
void *content = boost::unsafe_any_cast<void *>(&any_value);
The header has this to say about 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.

Related

QVariant wrapped pointers turn to null in QML

It seems like something is going wrong when pointer values transcend between C++ and QML world. I am using the plain old fromValue() and value() to convert to and from void *, and it does work as expected as long as the variant stays on the C++ side.
The moment it is returned to QML, it now resolves to null, and when passed back to C++, the variant type is changed from void * to std::nullptr_t and the value is null.
returning 0x3ba5b10 // created
converting to qvariant 0x3ba5b10 // converting
converted QVariant(void*, 0x3ba5b10) 0x3ba5b10 // now variant, testing value() - all good
qml: null // in qml
received QVariant(std::nullptr_t, (nullptr)) 0x0 // back in c++
I am using:
Q_DECLARE_METATYPE(void*)
qRegisterMetaType<void*>();
Any clue as to what is going on here?
Edit: it keeps even more strange, I get it to work by casting the pointer values to 64 bit uint and back, but upon the transition to QML, the type info gets messed up, in C++ the variant is of type qulonglong, arriving back from QML it is now a double, hence the suspicion it might round something and mess up the pointer value.
Edit 2: note that the question is not about recommending practices but about why this doesn't work as expected and observed prior to reaching QML.
You don't need to register void*, rather use the metatype QMetaType::VoidStar.
Note that to register the metatype SomeCustomType*, you need to use an alias.
using SomeCustomTypePtr = SomeCustomType*;
Q_DECLARE_METATYPE(SomeCustomTypePtr)
qRegisterMetaType<SomeCustomTypePtr>();
Isn't even possible to do such declarations?
According to official documentation on Q_DECLARE_METATYPE(Type):
This macro makes the type Type known to QMetaType as long as it provides a public default constructor, a public copy constructor and a public destructor. It is needed to use the type Type as a custom type in QVariant.
This macro requires that Type is a fully defined type at the point where it is used.
Sounds strange that this works at least in C++ part.
Don't you think that it will be better and straight-forward solution to declare your type pointer instead of void*?

Is there a legitimate use for void*?

Is there a legitimate use of void* in C++? Or was this introduced because C had it?
Just to recap my thoughts:
Input: If we want to allow multiple input types we can overload functions and methods, alternatively we can define a common base class, or template (thanks for mentioning this in the answers). In both cases the code get's more descriptive and less error prone (provided the base class is implemented in a sane way).
Output: I can't think of any situation where I would prefer to receive void* as opposed to something derived from a known base class.
Just to make it clear what I mean: I'm not specifically asking if there is a use-case for void*, but if there is a case where void* is the best or only available choice. Which has been perfectly answered by several people below.
void* is at least necessary as the result of ::operator new (also every operator new...) and of malloc and as the argument of the placement new operator.
void* can be thought as the common supertype of every pointer type. So it is not exactly meaning pointer to void, but pointer to anything.
BTW, if you wanted to keep some data for several unrelated global variables, you might use some std::map<void*,int> score; then, after having declared global int x; and double y; and std::string s; do score[&x]=1; and score[&y]=2; and score[&z]=3;
memset wants a void* address (the most generic ones)
Also, POSIX systems have dlsym and its return type evidently should be void*
There are multiple reasons to use void*, the 3 most common being:
interacting with a C library using void* in its interface
type-erasure
denoting un-typed memory
In reverse order, denoting un-typed memory with void* (3) instead of char* (or variants) helps preventing accidental pointer arithmetic; there are very few operations available on void* so it usually require casting before being useful. And of course, much like with char* there is no issue with aliasing.
Type-erasure (2) is still used in C++, in conjunction with templates or not:
non-generic code helps reducing binary bloat, it's useful in cold paths even in generic code
non-generic code is necessary for storage sometimes, even in generic container such as std::function
And obviously, when the interface you deal with uses void* (1), you have little choice.
Oh yes. Even in C++ sometimes we go with void * rather than template<class T*> because sometimes the extra code from the template expansion weighs too much.
Commonly I would use it as the actual implementation of the type, and the template type would inherit from it and wrap the casts.
Also, custom slab allocators (operator new implementations) must use void *. This is one of the reasons why g++ added an extension of permitting pointer arithmatic on void * as though it were of size 1.
Input: If we want to allow multiple input types we can overload
functions and methods
True.
alternatively we can define a common base
class.
This is partially true: what if you can't define a common base class, an interface or similar? To define those you need to have access to the source code, which is often not possible.
You didn't mention templates. However, templates cannot help you with polymorphism: they work with static types i.e. known at compile time.
void* may be consider as the lowest common denominator. In C++, you typically don't need it because (i) you can't inherently do much with it and (ii) there are almost always better solutions.
Even further, you will typically end up on converting it to other concrete types. That's why char * is usually better, although it may indicate that you're expecting a C-style string, rather than a pure block of data. That's whyvoid* is better than char* for that, because it allows implicit cast from other pointer types.
You're supposed to receive some data, work with it and produce an output; to achieve that, you need to know the data you're working with, otherwise you have a different problem which is not the one you were originally solving. Many languages don't have void* and have no problem with that, for instance.
Another legitimate use
When printing pointer addresses with functions like printf the pointer shall have void* type and, therefore, you may need a cast to void*
Yes, it is as useful as any other thing in the language.
As an example, you can use it to erase the type of a class that you are able to statically cast to the right type when needed, in order to have a minimal and flexible interface.
In that response there is an example of use that should give you an idea.
I copy and paste it below for the sake of clarity:
class Dispatcher {
Dispatcher() { }
template<class C, void(C::*M)() = C::receive>
static void invoke(void *instance) {
(static_cast<C*>(instance)->*M)();
}
public:
template<class C, void(C::*M)() = &C::receive>
static Dispatcher create(C *instance) {
Dispatcher d;
d.fn = &invoke<C, M>;
d.instance = instance;
return d;
}
void operator()() {
(fn)(instance);
}
private:
using Fn = void(*)(void *);
Fn fn;
void *instance;
};
Obviously, this is only one of the bunch of uses of void*.
Interfacing with an external library function which returns a pointer. Here is one for an Ada application.
extern "C" { void* ada_function();}
void* m_status_ptr = ada_function();
This returns a pointer to whatever it was Ada wanted to tell you about. You don't have to do anything fancy with it, you can give it back to Ada to do the next thing.
In fact disentangling an Ada pointer in C++ is non-trivial.
In short, C++ as a strict language (not taking into account C relics like malloc()) requires void* since it has no common parent of all possible types. Unlike ObjC, for example, which has object.
The first thing that occurs to my mind (which I suspect is a concrete case of a couple of the answers above) is the capability to pass an object instance to a threadproc in Windows.
I've got a couple of C++ classes which need to do this, they have worker thread implementations and the LPVOID parameter in the CreateThread() API gets an address of a static method implementation in the class so the worker thread can do the work with a specific instance of the class. Simple static cast back in the threadproc yields the instance to work with, allowing each instantiated object to have a worker thread from a single static method implementation.
In case of multiple inheritance, if you need to get a pointer to the first byte of a memory chunk occupied by an object, you may dynamic_cast to void*.

How to deal with a generic object in C++

What is the proper way to deal with a generic value in C++11 or is it OK to use (void *)?
Basically, I am parsing json, and the node value can either be String, Integer, Double, Date, etc.
In C, just using void * is OK (not safe, but ok), and in C# we use Object. But what is the proper way in C++11 to do this? Do I have to build a wrapper class, or is there an easier way?
You can make a base class for the various types, or use a "discriminated union" class such as Boost.Variant which holds a known set of types and remembers which one it is holding.

Is there a way to have a function return a type?

I have a data class (struct actually) two variables: a void pointer and a string containing the type of the object being pointed to.
struct data{
void* index;
std::string type;
data(): index(0), type("null"){}
data(void* index, std::string type): index(index), type(type){}};
Now I need to use the object being pointed to, by casting the void pointer to a type that is specified by the string, so I thought of using an std::map with strings and functions.
std::unordered_map<std::string, function> cast;
The problem is that the functions must always have the exact same return-type and can't return a type itself.
Edit:
Because I use the data class as a return-type and as arguments, templates won't suffice.
(also added some code to show what I mean)
data somefunction(data a){
//do stuff
return data();}
Currently, I use functions like this to do the trick, but I thought it could be done more easily:
void functionforstring(data a){
dynamic_cast<string*>(data.index)->function();}
Neither thing is possible in C++:
Functions cannot return types (that is to say, types are not values).
Code cannot operate on objects whose type it doesn't know at compile-time (that is to say, C++ is statically typed). Of course there is dynamic polymorphism via virtual functions, but even with that, the type of the pointer you use to call them is known at compile time by the calling code.
So the operation you want, "convert to the pointer type indicated by a string" is not possible. If it were possible, then the result would be a pointer whose type is not known at compile time, and that cannot be.
There's nothing you could do with this "pointer of type unknown at compile time", that you can't do using the void* you started with. void* pretty much already is what C++ has in place of a pointer to unknown type.
While it's not possible to return a type from a function, you could use typeid to get information about the object, and use the string returned by typeid(*obj).name() as an argument to your constructor.
Keep in mind that this string would be implementation defined, so you would have to generate this string at runtime for every type that you might possibly use in the program in order to make your unordered_map useful.
There is almost certainly a much simpler and more idiomatic way to accomplish your goal in C++, however. Perhaps if you explained more about the goals of the program, someone might be able to suggest an alternative approach.

How to let compiler examine data type manually without C++11

void f(string str,int i )
{
cout<<str.c_str()<<endl;
cout<<i<<endl;
}
typedef void (*PF)(int i,string str);
int _tmain(int argc, _TCHAR* argv[])
{
PF pf=(PF)(void*)&f;
pf(10,string()); //runtime-error
return 0;
}
Due to some needs, I need to call the function f using the address of f which data type has been erased (such as the code above). But this solution may cause the insecure function call because the data type can't be checked during the compiling.
Is there some ways to let the compiler to report an error when the the type of parameters are different from arguments'?
Something like this:
void f(T1 i,T2 j)
{
T1 p* = new i.real_type; //if i.real_type is different from T1, it will lead a compiling
....
}
I appreciate that very much.
The only run-time type information available in C++ is typeid and dynamic_cast, and they only work on polymorphic types (class types with virtual functions). Function pointers don't store the necessary information.
Really, you should just avoid casting function pointers. The only place a function pointer case is ever necessary is on the return value from GetProcAddress or dlsym.
No. There is no safe way to "get the type" from void*. There is likely a clean way to solve your actual problem so that void* is not needed. I suggestiv you post a new question there you explain your specific task.
Is there some ways to let the complier to report a error when the the type of parameters are different from arguments'.
How could it know? You subverted the type system (that's what casts to void*s do). You told the C++ compiler to pretend that a function pointer was a pointer to anything, then you told it to pretend that this pointer to anything was a pointer to a different type of function.
The compiler has no way of knowing what the original type was. All it knows is that there's a void*, and you asked to convert it to something. In order to allow void* to work at all, the C++ language doesn't require the compiler to magically know where a void* came from and what it used to be. Therefore, you can cast it to anything, but the specification states that if what you cast it to isn't the original type, you get undefined behavior.
The type system in C++ is what allows the compiler to detect when you've done something wrong. By subverting it, and subsequently doing it wrong, you have given up all rights to live in a rational universe. You told the compiler, "I know what I'm doing", then shot yourself in the foot.
The best you can do is use Boost.Any to store your function pointer. Any attempt to cast it to anything except what was originally stored in it will throw an exception. At runtime, of course.
Depending on the variety of function types you have, you add something for test or debug builds:
// Once off init call
DEBUG_INSERT (&f, INT_STRING);
...
DEBUG_CHECK_FUNC (pf, INT_STRING);
pf(10,string()); //runtime-error
I'm pretty sure that with some boost and/or c++11 magic you could remove the need to have a "KIND" and have that deduced implicitly from the original function type. You could probably end up with your call looking as follows:
CHECKED_CALL (pf, 10, string ());
Where in release builds it just calls the function with the arguments and in debug builds you get the checking too.