在仔细阅读网页和乱搞之后,我似乎无法将空*的目标(它是一个字符串)转换为std::string。我尝试过使用this page推荐的sprintf(buffer, "%p", *((int *)point));
来获取C字符串,但没有效果。不幸的是,是的,我必须使用空*,因为这就是SDL在他们的USEREVENT结构中使用的。
对于感兴趣的人,我用来填充Userevent的代码是:
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*。我真傻。非常感谢你们!
发布于 2010-06-20 03:58:07
您只需要动态分配它(因为它可能需要比您使用它的作用域更长的时间),然后来回转换它:
// 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;
发布于 2010-06-20 03:57:29
根据您的评论“我的意思是将void*指向的内容(这是一个字符串)转换为字符串。”
假设你有这个:
std::string str = ...;
void *ptr = &str;
您可以直接转换回字符串:
std::string *pstr = static_cast<std::string *>(ptr);
请注意,验证ptr
是否实际指向std::string
是您的责任。如果你错了,它指向了其他东西,这将导致未定义的行为。
发布于 2010-06-20 03:43:48
如果尝试将地址格式化为文本,则可以使用stringstream
std::stringstream strm;
strm << ptr;
std::string str = strm.str();
// str will now have something like "0x80004567"
如果这不是你感兴趣的,请澄清你的问题。
https://stackoverflow.com/questions/3076968
复制相似问题