将void *转换为std :: string

时间:2010-06-19 19:41:57

标签: c++ string printf void-pointers

在仔细阅读网页并弄乱自己之后,我似乎无法将void *的目标(这是一个字符串)转换为std :: string。我尝试使用this page推荐的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 个答案:

答案 0 :(得分:19)

你只需要动态分配它(因为它可能需要比你正在使用它的范围更长),然后来回投射它:

// 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;

答案 1 :(得分:7)

根据你的评论“我的意思是将void *指向的字符串(字符串)转换为字符串。”

假设你有这个:

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

你可以回转到字符串:

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

请注意,您需要确认ptr实际指向std::string。如果你错了,它指向其他东西,这将导致未定义的行为。

答案 2 :(得分:5)

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

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

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

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

答案 3 :(得分:1)

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

const char* cakes = something;
std::string lols = std::string(cakes);