C、硬件抽象层中“extern”类型的变量
我正在研究硬件抽象层。此 HAL 的目的是在 Linux 驱动程序和 MCU 驱动程序之间轻松切换。
我正在研究 SPI 接口。下面是HAL“打开”SPI接口的函数签名。
hal/spi.h
spi_handle_t spi_open(spi_port_t channel, spi_config_t config);
spi_port_t :
- 在 Linux 上,它是一个基本类型:uint32_t
- 在 MCU 上,它是一个结构体。
spi_config_t :
- 在 Linux 和 MCU 上,它都是一个结构体,但具有不同的字段。
所以在mcu/spi.c 中,我在某个时候有:
typedef spiBASE_t spi_channel_t;
typedef spiDAT1_t spi_config_t;
spi_handle_t spi_open(spi_channel_t channel, spi_config_t config) {
.
.
.
}
对于linux/spi.c:
typedef uint32_t spi_channel_t;
typedef ChannelConfig_t spi_config_t;
spi_handle_t spi_open(spi_channel_t channel, spi_config_t config) {
.
.
.
}
现在问题出在hal/spi.h 中,我需要定义什么是 spi_channel_t 和 spi_config_t。
有没有办法制作类似的东西(我知道用 extern 是不可能的,但为了解释问题......):
extern spi_channel_t;
extern spi_config_t;
这会对编译器说:“好吧,头文件中没有定义这两种类型,您仍然可以在我传递给工具链的文件之一上找到它们的存储大小”。
回答
您似乎正在寻找一种称为opaque type的技巧。这是一种使用结构体的前向声明来实现 C 中的私有封装和多态性的方法。它通常用于专业编写的嵌入式系统驱动程序,可以像这样实现:
hal/spi.h
// forward declaration of a struct, with typedef and struct tag:
typedef struct spi_handle_t spi_handle_t;
// Require the caller to declare a spi_handle_t* pointer, not an object:
spi_handle_t* spi_init (...);
单片机/spi.c
struct spi_handle_t
{
// whatever you need here - these are now 100% private members
};
spi_handle_t* spi_init (...)
{
spi_handle* result = address_of_some_static_memory_pool;
/* init struct members here */
return result;
}
linux/spi.c
struct spi_handle_t
{
uint32_t something;
// whatever you need here - these are now 100% private members
};
spi_handle_t* spi_init (...)
{
spi_handle* result = malloc(sizeof *result); // malloc is fine to use in Linux
/* init struct members here */
return result;
}
现在调用者必须将 传递spi_handle*给驱动程序中的其他函数。这不仅对 OO 设计很方便,而且还可以使用多个实例运行相同的代码。例如,如果您在 MCU 上有 2 个不同的 SPI 硬件外设,并希望以不同的方式使用它们,但使用相同的驱动程序代码。