15

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?

Austin Henley
  • 4,625
  • 13
  • 45
  • 80
ghiboz
  • 7,863
  • 21
  • 85
  • 131
  • Pass your string like this- `strdup(str.c_str())` or, `strdup(chArr)`. From callback function use like this- `std::string str = std::string((char*)voidData);` or, `char* chArr = (char*) voidData;` – Minhas Kamal Apr 21 '20 at 11:57

3 Answers3

11

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!

Seb Holzapfel
  • 3,793
  • 1
  • 19
  • 22
9

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
4

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458