在 switch case 节点中将 const int 指针转换为 int

Cast const int pointer to int, in a switch case node

在我的 STM32 代码中有一个

#define USART1              ((USART_TypeDef *) USART1_BASE)

我想要

switch((uint32_t)ptr)
{
  case USART1: return 1;
(...)

但是gcc-arm (6.3.1) 报错

error: reinterpret_cast from integer to pointer

我找到了可以使用的信息

  case __builtin_constant_p(USART1): return 0;

但这只是 gcc 解决方案?有没有更通用的东西?

USART1_BASE是STM32开发环境头文件中的一个数字。当你决定在开关中使用什么类型时,你可以编译你的代码。我推荐 uint32_t:

switch((uint32_t)ptr)
{
  case USART1_BASE: return 1;
  (...)

如果你想要更多的可读性,你可以尝试从 switch 中删除强制转换:

uint32_t ptr_value = (uint32_t)ptr;

switch(ptr_value)
{
  case USART1_BASE: return 1;
  (...)

UART1_BASE,它只是几个无符号整数常量的总和。看机头:

#define PERIPH_BASE           0x40000000U
#define APB2PERIPH_BASE       (PERIPH_BASE + 0x00010000U)
#define USART1_BASE           (APB2PERIPH_BASE + 0x1000U)

所以应该可以用

switch((unsigned int)ptr) {
    case USART1_BASE: return 1;
}

您也忘记在 case 语句中将指针强制转换为整数。 我的工作代码示例:

switch ((uint32_t)gpio) {
    case (uint32_t)GPIOA:
        EXTI_cfgr = 0b0000;
        break;
    case (uint32_t)GPIOB:
        EXTI_cfgr = 0b0001;
        break;
    case (uint32_t)GPIOC:
        EXTI_cfgr = 0b0010;
        break;
    default:
        break;
    }