簡體   English   中英

每個結構調用使用一次的結構函數指針

[英]Function Pointers to Struct Used Once Per Struct-Call

我有一個包含幾個函數指針的結構。 通用接口在頭文件中生成。

頭文件

typedef struct
{
    void (*Start)(void);
    void (*ByteWrite)(uint8_t *pBuffer);        // Modifies I2C buffer
    uint8_t (*ByteRead)(uint8_t *pBuffer);
    void (*ArrayWrite)(uint8_t *pBuffer);
    uint8_t (*ArrayRead)(uint8_t *pBuffer);
    bool (*Busy)(void);
} sI2C_t;


extern const sI2C_t I2C0;
extern const sI2C_t I2C1;
extern const sI2C_t I2C2;

然后在C文件中實現每個函數指針以滿足結構接口。

C檔案

static void I2C0_Start(void) { ... }
static void I2C0_ByteWrite(*uint8_t) { ... }
static uint8_t I2C0_ByteRead(*uint8_t) { ... }
static void I2C0_ArrayWrite(*uint8_t) { ... }
static uint8_t I2C_ArrayRead(*uint8_t) { ... }
static bool I2C_Busy(void) { ... }

const sI2C I2C0 =
{
    I2C0_Start,
    I2C0_ByteWrite,
    I2C0_ByteRead,
    I2C0_ArrayWrite,
    I2C0_ArrayRead,
    I2C0_Busy
};

// Code-block repeated for I2C1, I2C2, etc. (REDUNDANT!)

這使得訪問I2C接口特定功能變得相對容易:

bool status;

I2C0.Start();
status = I2C1.Busy();
...

雖然函數指針對於I2C0,I2C1和I2C2等基本相同,但我必須為每個新的結構接口單獨寫出它們。 由於這是多余的,我有沒有辦法只實現一次這些函數指針?

標准解決方案是將結構指針作為第一個參數傳遞給函數。 即代替:

I2C0.Start();

你寫:

I2C0.Start(&I2C0);

然后,您可以向結構添加一些額外的字段以標識它是哪一個(例如,如果每個I2C總線都有固定的硬件地址,則可能在結構的額外字段中具有硬件地址)。

這是執行C ++類等效的常規C方式。

你可以編寫一個構造函數。 例:

typedef struct{
     int    a;
     char   b;
}example;

void constructor (example *pointer_to_struct, int a_value, char b_value){
    pointer_to_struct->a = a_value;
    pointer_to_struct->b = b_value;   /*remember: if you have strings don't have any 
                                     assignments, since a string (like any other array) is a pointer to 
                                     its first element*/
}


int main (void){

    example ex_struct;
    constructor(&ex_struct, 10, 'C');

    return 0;
}

編輯:您還可以編寫一個函數,為所選類型的每個結構進行相同的分配。 例:

void constructor(structure *p){
     p->a = 10;
     p->b = 'C';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM