I'm storing a pointer to a function as a string:
//callback = std::function<void()> callback
std::stringstream cbPtrToString;
cbPtrToString << &callback;
std::string prtString = cbPtrToString.str();
How can I convert prtString
back into a callable function? I've tried this below, but it doesn't do what I thought it would do.
std::stringstream stringToPtr(ptrString);
void* result;
stringToPtr >> result;
result();
Following your example, you have std::function<void()>
as your callback. I would first suggest you make that a typedef and some simple conversion functions:
typedef std::function<void()> CallbackType;
std::string CallbackToString(const CallbackType* cb)
{
std::ostringstream oss;
oss << reinterpret_cast<uintptr_t>(cb);
return oss.str();
}
const CallbackType* StringToCallback(const std::string& str)
{
std::istringstream iss(str);
uintptr_t ptr;
return (iss >> ptr) ? reinterpret_cast<CallbackType*>(ptr) : nullptr;
}
It is allowed by the C++ standard to convert from pointer types to uintptr_t
and back, and provided these values are only used within the same process it is probably acceptable to do so.
You must ensure that your functions actually exist, however. In this live example, they're stored on the stack in main
. However, if you were to create them as temporaries and then use those pointers after the objects had been destroyed, it would be bad.
If you don't want to be reinterpreting pointers, then as already suggested in the comments you could store some other kind of tokens such as keeping a table of all your callbacks and then just storing the table index. That would be considered a cleaner solution.