4

いくつかの関数ポインタを含む構造体があります。汎用インターフェースはヘッダーファイルで作成されます。

ヘッダーファイル

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などで同じですが、新しい構造体インターフェイスごとに個別に書き出す必要があります。これは冗長なので、これらの関数ポインターを1回だけ実装する方法はありますか?

4

2 に答える 2

0

コンストラクタ関数を記述できます。例:

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';
}
于 2013-03-17T09:07:17.933 に答える