4

What is the best/safest way to cast void* to char* in c++?

static_cast or reinterpret_cast?

void I2C::Read(void* buffer, DWORD address, UINT size) 
{
    if (_isDeviceAvailable)
    {
        _iicInstance.seekg(address, std::ios_base::beg);
        _iicInstance.read(reinterpret_cast<char *>(buffer), size);
        Gpio::SVSet();
    }

}

Community
  • 1
  • 1
Smit Ycyken
  • 1,189
  • 1
  • 11
  • 25

1 Answers1

7

static_cast would be the choice here. Using static_cast to and from a void* preserves the adress, see a similar question here.

The accepted answer also explains why not to use reinterpret_cast in similar situations.

Community
  • 1
  • 1
sweerpotato
  • 470
  • 2
  • 11
  • 22
  • Ty, [this](http://stackoverflow.com/questions/573294/when-to-use-reinterpret-cast/573345#573345) is great explanation, better than msdn. – Smit Ycyken Sep 23 '15 at 05:58
  • 3
    Thanks for pointing out the question. I have closed this thread based on that. BTW, your answer is true, but the reasoning is wrong. With C++11, both `static_cast` and `reinterpret_cast` do the same thing. However, one should use `static_cast` wherever possible on `reinterpret_cast`. Usually the latter is used, when casting between altogether different types; e.g. `long` to `X*`. IMO, below is the ugliness index of casts (least to most): `dynamic_cast`, `const_cast`, `static_cast`, `reinterpret_cast`, *"C-style cast"*. – iammilind Sep 23 '15 at 05:58
  • I see! Thank you for the clarification. Should I edit my answer into something more appropriate? – sweerpotato Sep 23 '15 at 06:08