【问题标题】:How to switch on HINSTANCE without resorting to const_cast?如何在不使用 const_cast 的情况下打开 HINSTANCE?
【发布时间】:2019-08-03 02:46:28
【问题描述】:

标题已经说过了。

查看真实世界示例,请参阅:https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-findexecutablea

返回一个 HINSTANCE - 它是一个指针类型 - 在某些情况下可以假定预定义的错误值。

最好是,我想打开一个 HINSTANCE 并在不诉诸 const_cast 或 c 样式转换的情况下做到这一点 - 如何实现?

示例代码:

bool test_result(const HINSTANCE ptr) {
  switch (ptr) {
  case 2 /*SE_ERR_FNF*/:
    return false;
  default:
    return true;
  }
}

【问题讨论】:

  • 为什么是switch?为什么不if (hInst == (HINSTANCE)SE_ERR_FNF) { ... }
  • @RogerLipscombe 很好,在实践中还有更多的价值/案例

标签: c++ casting switch-statement c++17


【解决方案1】:

我自己做了一些测试,因为该返回类型没有多大意义,但无论出于何种原因,WinAPI 实际上确实返回void*。在这种情况下,实际返回值是void* 指向的地址。所以你可以使用reinterpret_cast 投射它并打开它:

bool test_result(const HINSTANCE ptr) {
  switch (reinterpret_cast<uintptr_t>(ptr)) {
  case 2 /*SE_ERR_FNF*/:
    return false;
  default:
    return true;
  }
}

【讨论】:

  • 你可以投到reinterpret_cast吗?
  • @Bathsheba 现在我们正在动态施放你,让我们用一块石头得到 2 只鸟,然后找出答案。
  • 与此同时,我也发现了这一点-duh
  • 不要背叛我,当你得到 mod 时开始删除我非常有用的 cmets。
  • @SombreroChicken 你认为 intptr_t 或 uintptr_t 在这里更合适,因为它来自指针
【解决方案2】:

用于将指针(HINSTANCE 只是一个 void*)转换为 int,您将 reinterpret_cast 转换为 uintptr_t。像这样:

bool test_result(const HINSTANCE ptr)
{
  switch (reinterpret_cast<uintptr_t>(ptr))
  {
  case 2 /*SE_ERR_FNF*/:
    return false;
  default:
    return true;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-06
    • 2019-03-13
    • 2020-10-27
    • 2018-06-05
    • 1970-01-01
    • 2020-11-09
    • 2011-05-15
    • 2012-01-26
    相关资源
    最近更新 更多