Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a void* to a std::string

After perusing the web and messing around myself, I can't seem to convert a void*'s target (which is a string) to a std::string. I've tried using sprintf(buffer, "%p", *((int *)point)); as recommended by this page to get to a C string, but to no avail. And sadly, yes, I have to use a void*, as that's what SDL uses in their USEREVENT struct.

The code I'm using to fill the Userevent, for those interested, is:

std::string filename = "ResumeButton.png"; SDL_Event button_press; button_press.type = BUTTON_PRESS; button_press.user.data1 = &filename; SDL_PushEvent(&button_press); 

Any ideas?

EDIT: Thanks for all the responses, I just needed to cast the void* to a std::string*. Silly me. Thank you guys so much!

like image 984
Lewis Avatar asked Jun 19 '10 19:06

Lewis


People also ask

Can Void be converted to int?

You're return ing the value of int sum by setting a void * address to it. In this case, the address is not valid. But, if you keep that in mind and get the value of sum by casting a void * to int it will work.


2 Answers

You just need to dynamically allocate it (because it probably needs to outlive the scope you're using it in), then cast it back and forth:

// Cast a dynamically allocated string to 'void*'. void *vp = static_cast<void*>(new std::string("it's easy to break stuff like this!"));  // Then, in the function that's using the UserEvent: // Cast it back to a string pointer. std::string *sp = static_cast<std::string*>(vp); // You could use 'sp' directly, or this, which does a copy. std::string s = *sp; // Don't forget to destroy the memory that you've allocated. delete sp; 
like image 133
Stephen Avatar answered Sep 18 '22 14:09

Stephen


Based on your comment "What I meant was to convert what the void* is pointing to (which is a string) into a string."

Assuming you have this:

std::string str = ...; void *ptr = &str; 

You can just cast back to the string:

std::string *pstr = static_cast<std::string *>(ptr); 

Note that it is on you to verify that ptr actually points to a std::string. If you are mistaken and it points to something else, this will cause undefined behavior.

like image 28
R Samuel Klatchko Avatar answered Sep 18 '22 14:09

R Samuel Klatchko