2017-03-16 34 views
0

您是否有任何关于在C++中实现硬件抽象层的设计模式或技术的建议,以便我可以在构建时轻松切换平台?我正在考虑使用类似我在GoF或C++模板中阅读的桥模式,但我不确定这是否是最佳选择。C++中用于HAL实现的设计模式

回答

1

我认为在构建时使用桥接模式并不是一个好的选择。

这是我的解决方案:

定义一个标准设备类作为接口:

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 

对于ARM平台:

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

使用t HESE设备:

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

编译选项:

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

如果无论如何你知道编译时的目标CPU,为什么诉诸动态多态?你从每一方都输了! –

+0

同意!另外,SFINAE over #ifdef – Jeff

+0

X86和ARM只是一个例子,你可以用PAX255,IT3354来代替它们。对于一个设备来说,不同平台的驱动程序的源代码除了一些关键点之外几乎与初始化过程相同。我可以将所有这些代码写入一个类或文件中的不同平台,但在代码维护@DavidHaim – netdigger