简体   繁体   English

从字符串转换为void *并返回

[英]Casting from string to void* and back

is possible to re-map STL class object from void* ? 可以从void *重新映射STL类对象吗?

#include <string>

void func(void *d)
{
    std::string &s = reinterpret_cast<std::string&>(d);
}

int main()
{
    std::string s = "Hi";
    func(reinterpret_cast<void*>(&s));
}

Use static_cast to convert void pointers back to other pointers, just be sure to convert back to the exact same type used originally. 使用static_cast将void指针转换回其他指针,只需确保转换回原来使用的完全相同的类型。 No cast is necessary to convert to a void pointer. 转换为void指针不需要强制转换。

This works for any pointer type, including pointers to types from the stdlib. 这适用于任何指针类型,包括指向stdlib中类型的指针。 (Technically any pointer to object type, but this is what is meant by "pointers"; other types of pointers, such as pointers to data members, require qualification.) (从技术上讲,任何指向对象类型的指针,但这都是“指针”的含义;其他类型的指针,如指向数据成员的指针,需要进行限定。)

void func(void *d) {
  std::string &s = *static_cast<std::string*>(d);
  // It is more common to make s a pointer too, but I kept the reference
  // that you have.
}

int main() {
  std::string s = "Hi";
  func(&s);
  return 0;
}

I re-wrote as following, 我重写如下,

#include<string>

void func(void *d)
{
    std::string *x = static_cast<std::string*>(d);
/* since, d is pointer to address, it should be casted back to pointer
   Note: no reinterpretation is required when casting from void* */
}

int main()
{
    std::string s = "Hi";
    func(&s); //implicit converssion, no cast required
}

You code shouldn't compile. 你的代码不应该编译。 Change 更改

std::string &s = reinterpret_cast<std::string&>(d);

to

std::string *s = static_cast<std::string*>(d);

EDIT: Updated code. 编辑:更新的代码。 Use static_cast instead of reinterpret_cast 使用static_cast而不是reinterpret_cast

Yes, it is possible, but you are trying to cast from a pointer to void * , then to a reference . 是的,这是可能的,但是你试图从指向void *的指针转换为引用 The reinterpret_cast operator only allows casting back to exactly the same type that you started with. reinterpret_cast运算符仅允许回送到与您开始时完全相同的类型。 Try this instead: 试试这个:

void func(void *d)
{
    std::string &s = *reinterpret_cast<std::string*>(d);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM