【问题标题】:Casting void* to char* [duplicate]将 void* 转换为 char* [重复]
【发布时间】:2015-12-20 07:29:33
【问题描述】:

在 c++ 中将 void* 转换为 char* 的最佳/最安全方法是什么?

static_cast 还是 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();
    }

}

【问题讨论】:

  • C++ 中没有PVOIDPCHAR。也许您打算用特定的实现标签来标记这个问题? :-)
  • void*char* 将是相同的大小,所以你所要做的就是投射它。
  • 所以不管使用什么演员阵容?
  • 在这种特殊情况下,两个演员做同样的事情。

标签: c++ casting char void


【解决方案1】:

static_cast 将是这里的选择。在void* 之间使用static_cast 可以保留地址,请参阅类似的问题here

accepted answer 还解释了为什么不在类似情况下使用reinterpret_cast

【讨论】:

  • Ty, this 解释得很好,比 msdn 好。
  • 感谢您指出问题。我已经基于此关闭了此线程。顺便说一句,你的回答是对的,但推理是错误的。对于 C++11,static_castreinterpret_cast 都做同样的事情。但是,应尽可能在reinterpret_cast 上使用static_cast。当在完全不同的类型之间进行转换时,通常使用后者;例如longX*。 IMO,以下是演员表的丑陋指数(最少到最多):dynamic_castconst_caststatic_castreinterpret_cast“C 风格演员表”
  • 我明白了!谢谢你的澄清。我应该把我的答案编辑成更合适的吗?
猜你喜欢
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多