替代C 中的内类

Alternative to Inner Classes in C++

本文关键字:替代      更新时间:2023-10-16

假设我正在为BCM2835 rpi芯片编写一个"设备树斑点",但在C 文件中,而不是.dts文件。目的是练习C 和OS概念。

我希望能够不仅封装登记地址,而且可以访问访问这些地址的函数,并仅将顶级用作用作API函数。

C++中,这可能是内部类

//bcm2835.h
class BMC2835 : public ARMCpu
{
public:
    void ACKLedOn(void);
    void ACKLdOff(void);
    void ACKLedBlink(void);
    // I2C write to device (this would be called by the device driver)
    // It would ensure that I2C is setup, etc, etc
    void I2C_Device_Write(I2C_Device* device, uint8_t* buffer);
private:
    // Physical addresses for various peripheral register sets
    /// Base Physical Address of the BCM 2835 peripheral registers
    const uint32_t BCM2835_PERI_BASE       = 0x20000000;
    class GPIO()
    {
    private:
       /// Base Physical Address of the Pads registers
       const uint32_t BCM2835_GPIO_PADS    = (BCM2835_PERI_BASE + 0x100000)
       /// Sets the Function Select register for the given pin, which configures
       /// the pin as Input, Output or one of the 6 alternate functions.
       void bcm2835_gpio_fsel(uint8_t pin, uint8_t mode);
    }
    class I2C()
    {
       private:
           const uint32_t BCM2835_CORE_CLK_HZ    = 250000000  ;///< 250 MHz
           // Register masks for BSC_C
           const uint32_t BCM2835_BSC_C_I2CEN    = 0x00008000;///< I2C Enable, 0 = disabled, 1 = enabled
           const uint32_t BCM2835_BSC_C_INTR     = 0x00000400;///< Interrupt on RX
           const uint32_t BCM2835_BSC_C_INTT     = 0x00000200;///< Interrupt on TX
           void bcm2835_i2c_begin(void);
           void bcm2835_i2c_write(uint8_t address, uint8* pbuffer);
    }
}

,然后我也可以为BCM2837提供一个类,该类别为64位,例如对LED的处理非常不同。

//bcm2837.h
class BCM2837 : public ARMCpu
{
    public:
        // LED is now a very different Implementation with Mailbox
        // but exposed to Kernel as API
        void ACKLedOn(void);
        void ACKLdOff(void);
        void ACKLedBlink(void);
    ...
    ...
}

我敢肯定,这种方法有很多问题。似乎最困扰我的是单个类的长度,包括 SPIUART等,等等。

即使ARMCpu良好地态和100%虚拟(我宁愿在嵌入式中避免),每个CPU类仍将相当冗长且难以阅读和维护。

有没有办法在C 中实现此类私人级别访问?

将每个芯片放在自己的.cpp文件中,并在该文件中声明所有这些私人的内部内容(而不是标题中)。您可以将它们包裹在匿名名称空间中,以防止它们暴露于链接器。