Converting a void* to a std::string

后端 未结 4 2011
深忆病人
深忆病人 2020-12-29 20:32

After perusing the web and messing around myself, I can\'t seem to convert a void*\'s target (which is a string) to a std::string. I\'ve tried using sprintf(buffer, \"

相关标签:
4条回答
  • 2020-12-29 20:55

    You just need to dynamically allocate it (because it probably needs to outlive the scope you're using it in), then cast it back and forth:

    // 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;
    
    0 讨论(0)
  • 2020-12-29 20:57

    If the void is a const char*, then you can just call the std::string constructor with it, i.e.

    const char* cakes = something;
    std::string lols = std::string(cakes);
    
    0 讨论(0)
  • 2020-12-29 20:58

    If you trying to format the address as text you can use a stringstream:

    std::stringstream strm;
    strm << ptr;
    std::string str = strm.str(); 
    
    // str will now have something like "0x80004567"
    

    If that's not what you are interested in, please clarify your question.

    0 讨论(0)
  • 2020-12-29 21:08

    Based on your comment "What I meant was to convert what the void* is pointing to (which is a string) into a string."

    Assuming you have this:

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

    You can just cast back to the string:

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

    Note that it is on you to verify that ptr actually points to a std::string. If you are mistaken and it points to something else, this will cause undefined behavior.

    0 讨论(0)
提交回复
热议问题