I use a library that have a callback function where one of the parameters is of type void *
. (I suppose to let to send value of any type.)
I need to pass a string (std::string
or a char[]
is the same).
How can I do this?
If you're sure the object is alive (and can be modified) during the lifetime of the function, you can do a cast on a string pointer, turning it back into a reference in the callback:
#include <iostream>
#include <string>
void Callback(void *data) {
std::string &s = *(static_cast<std::string*>(data));
std::cout << s;
}
int main() {
std::string s("Hello, Callback!");
Callback( static_cast<void*>(&s) );
return 0;
}
Output is Hello, Callback!