【问题标题】:Converting a void* to a std::string将 void* 转换为 std::string
【发布时间】:2011-03-05 20:29:05
【问题描述】:

在浏览了网络并弄乱了自己之后,我似乎无法将 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*。傻我。非常感谢你们!

【问题讨论】:

  • 什么是STL,STL中的USEREVENT是什么? C++ 没有这样的东西。
  • 你想做什么?你有一个指向什么的 void* 指针?
  • 我认为他的意思是 SDL UserEvent linux.die.net/man/3/sdl_userevent
  • 向我们展示填充 UserEvent 结构的代码。
  • @Lewis :这里有问题。当您的事件处理程序运行时,filename 超出范围,user.data1 指向垃圾。您可能会出现段错误(尽管它可能按预期工作......一段时间......直到出现段错误)。看看我的回答,看看如何防止这种情况发生。

标签: c++ string printf void-pointers


【解决方案1】:

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

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

【讨论】:

  • 正是我想要的。谢谢!
  • 请注意,这个答案比其他答案有优势,因为它可以防止指针的目标超出范围。再次感谢!
【解决方案2】:

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

假设你有这个:

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

你可以直接转换回字符串:

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

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

【讨论】:

  • 这正是我想要的。非常感谢!
【解决方案3】:

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

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

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

如果您对此不感兴趣,请澄清您的问题。

【讨论】:

  • 对不起,我一点都不清楚。我的意思是将 void* 指向的内容(它是一个字符串)转换为一个字符串。
【解决方案4】:

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

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

【讨论】:

  • 您通常不能假设是这种情况,因此您的建议可能会导致分段违规。请考虑将其删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
相关资源
最近更新 更多