30

在仔细阅读网络并弄乱自己之后,我似乎无法将 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);

有任何想法吗?

编辑:感谢所有回复,我只需要将 void* 转换为 std::string*。傻我。非常感谢你们!

4

4 回答 4

28

您只需要动态分配它(因为它可能需要超过您使用它的范围),然后来回转换它:

// 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-19T19:58:07.167 回答
11

根据您的评论“我的意思是将 void* 指向的内容(它是一个字符串)转换为一个字符串。”

假设你有这个:

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

您可以只转换回字符串:

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

请注意,您需要验证它ptr实际上指向一个std::string. 如果你弄错了,它指向别的东西,这将导致未定义的行为。

于 2010-06-19T19:57:28.583 回答
5

如果您尝试将地址格式化为文本,您可以使用stringstream

std::stringstream strm;
strm << ptr;
std::string str = strm.str(); 

// str will now have something like "0x80004567"

如果这不是您感兴趣的,请澄清您的问题。

于 2010-06-19T19:43:48.180 回答
0

如果 void 是一个 const char*,那么你可以用它调用 std::string 构造函数,即

const char* cakes = something;
std::string lols = std::string(cakes);
于 2010-06-19T19:59:20.253 回答