Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 245
ghiboz Avatar asked Jan 27 '13 23:01

ghiboz


2 Answers

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!

like image 134
Seb Holzapfel Avatar answered Oct 21 '22 03:10

Seb Holzapfel


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.

like image 34
Kerrek SB Avatar answered Oct 21 '22 04:10

Kerrek SB