在C 中实现HAL的设计模式

Design pattern for HAL implementation in C++

本文关键字:设计模式 HAL 实现      更新时间:2023-10-16

您是否有关于在C 中实现硬件抽象层的设计模式或技术的建议,以便我可以在构建时间轻松地在平台之间切换?我正在考虑使用我在GOF或C 模板中阅读的桥梁图案之类的东西,但是我不确定这是最好的选择。

我认为在建筑时使用桥梁模式不是一个好选择。

这是我的解决方案:

将标准设备类定义为接口:

class Device {
    ... // Common functions
};

x86平台:

#ifdef X86 // X86 just is an example, user should find the platform define.
class X86Device: public Device{
    ... // special code for X86 platform
};
#endif

对于手臂平台:

#ifdef ARM // ARM just is an example, user should find the platform define.
class ARMDevice: public Device {
    ... // Special code for ARM platform
};
#endif

使用这些设备:

#ifdef X86
Device* dev = new X86Device();
#elif ARM
Device* dev = new ARMDevice();
#endif

编译选项:

$ g++ -DARM ... // using ArmDevice
$ g++ -DX86 ... // using X86Device

有关更多想法,请参阅此问题的答案:跨平台C 代码和单个标头 - 多个实现

当我面临类似问题时,我最终使用了pimpl成语。