C ++ convert string to void pointer
If you are sure that the object is alive (and can be changed) during the lifetime of the function, you can cast on the string pointer by 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 Hello, Callback!
source to share
If you have a char -array, it can be implicitly converted to a void pointer. 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 to std::string
highlight the function call expression.
source to share
If it is a callback function that you supply , you can simply pass the address of the objectstd::string
void f(void* v_str)
{
std::string* str = static_cast<std::string*>(v_str);
// Use it
}
...
...
std::string* str = new std::string("parameter");
register_callback(&f, str);
In any case, as Kerrek SB said, make sure the lifetime of the string object is not less than the length of time the callback is in use.
source to share