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!
If you have a char-array, then it can be converted to a void pointer implicitly. If you have a C++ string, you can take the address of the first element:
void f(void *); // example
#include <string>
int main()
{
char a[] = "Hello";
std::string s = "World";
f(a);
f(&s[0]);
}
Make sure that the std::string
outlives the function call expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With