Lew*_*wis 26 c++ string printf void-pointers
在仔细阅读网页并弄乱自己之后,我似乎无法将void*的目标(这是一个字符串)转换为std :: string.我尝试使用此页面的sprintf(buffer, "%p", *((int *)point));
建议来获取C字符串,但无济于事.遗憾的是,是的,我必须使用void*,因为这是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);
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
编辑:感谢所有的回复,我只需要将void*转换为std :: string*.傻我.非常感谢你们!
Ste*_*hen 22
你只需要动态分配它(因为它可能需要比你正在使用它的范围更长),然后来回转换它:
// 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;
Run Code Online (Sandbox Code Playgroud)
基于您的评论"我的意思是将void*指向的字符串(字符串)转换为字符串."
假设你有这个:
std::string str = ...;
void *ptr = &str;
Run Code Online (Sandbox Code Playgroud)
你可以回转到字符串:
std::string *pstr = static_cast<std::string *>(ptr);
Run Code Online (Sandbox Code Playgroud)
请注意,您可以验证ptr
实际指向a std::string
.如果你错了,它指向其他东西,这将导致未定义的行为.
如果您尝试将地址设置为文本格式,则可以使用stringstream
:
std::stringstream strm;
strm << ptr;
std::string str = strm.str();
// str will now have something like "0x80004567"
Run Code Online (Sandbox Code Playgroud)
如果那不是您感兴趣的内容,请澄清您的问题。