ghiboz
ghiboz

Reputation: 7993

c++ convert string into void pointer

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?

Upvotes: 16

Views: 31479

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 476940

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.

Upvotes: 9

Seb Holzapfel
Seb Holzapfel

Reputation: 3873

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!

Upvotes: 11

If it's a callback function that you supply, than you can simply pass the address of the std::string object

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);

Either way, like Kerrek SB said, make sure the lifetime of the string object is at least as long as the span of time the callback is in use.

Upvotes: 4

Related Questions