Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting from string to void* and back

Tags:

c++

casting

is possible to re-map STL class object from void* ?

#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));
}
like image 296
user963241 Avatar asked Jan 26 '11 12:01

user963241


1 Answers

Use static_cast to convert void pointers back to other pointers, just be sure to convert back to the exact same type used originally. No cast is necessary to convert to a void pointer.

This works for any pointer type, including pointers to types from the 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;
}
like image 174
Fred Nurk Avatar answered Oct 23 '22 11:10

Fred Nurk