将void *转换为std :: string [英] Converting a void* to a std::string
问题描述
在浏览网页和搞乱自己后,我似乎无法将void *的目标(这是一个字符串)转换为std :: string。我尝试使用 sprintf(buffer,%p,*((int *)point)); .daniweb.com / forums / thread221261.html>此页面获取C字符串,但无效。很遗憾,是的,我必须使用void *,因为这是SDL在USEREVENT结构中使用的。
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.
我用来填充Userevent的代码那些感兴趣的是:
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);
任何想法?
对于所有的响应,我只需要将void *转换为std :: string *。我傻。非常感谢你们!
Thanks for all the responses, I just needed to cast the void* to a std::string*. Silly me. Thank you guys so much!
推荐答案
你只需要动态分配它(因为它可能需要超出你的范围使用它),然后来回转换:
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;
这篇关于将void *转换为std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!