C ++ convert string to void pointer

I am using a library with a callback function where one of the parameters is of type void *

. (I suppose to send a value of any type.)

I need to pass a string ( std::string

or char[]

the same).

How can i do this?

+3


source to share


3 answers


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!

+5


source


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.

+4


source


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.

+2


source







All Articles