Skip to content

Instantly share code, notes, and snippets.

@chanlettuce
Created May 24, 2021 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chanlettuce/0096f8730fd9cf2f5a22e79d536e30ab to your computer and use it in GitHub Desktop.
Save chanlettuce/0096f8730fd9cf2f5a22e79d536e30ab to your computer and use it in GitHub Desktop.
functions_structs_array_sample
#include<stdio.h>
#include<string.h>
// プロダクトIDの定義一覧
#define CO2_7SEG_ID 0
#define SOIL_7SEG_ID 1
#define RESULT_CODE_SUCCESS 0
#define RESULT_CODE_FAILURE 1
// ここを書き換えることで製品設定が変わる
#define PRODUCT_ID CO2_7SEG_ID
/** グローバル変数等の初期化関数 */
typedef int InitFn();
/** センサーデータの読み取りと生の値を加工するための関数 */
typedef int ReadFn();
/** 出力処理関数 */
typedef int WriteFn();
/** 製品の型定義(関数ポインタの入っている構造体) */
struct Product {
int id;
InitFn *init;
ReadFn *read;
WriteFn *write;
};
// ======== 製品関数の定義 ========
int co2Init(){
printf("Hello, co2Init!\n");
return RESULT_CODE_SUCCESS;
}
int co2Read(){
printf("Hello, co2Read!\n");
return RESULT_CODE_SUCCESS;
}
int co2Write(){
printf("Hello, co2Write!\n");
return RESULT_CODE_SUCCESS;
}
// ======== 製品配列の定義 ========
struct Product products[] = {
// 関数ポインタになってるから構造体のポインタの配列にしなくてもいいかな?
{ 9999, NULL, NULL, NULL}, // ダミーのやつも入れてみる
{ CO2_7SEG_ID, co2Init, co2Read, co2Write}
};
// ====== 共通関数の実行部分 ======
struct Product *findProduct(int productId){
// すげーダサい
int arrayVolume = sizeof products / sizeof products[0];
for(int index = 0; index < arrayVolume; index++){
if(products[index].id == productId){
struct Product *ptr = &products[index];
return ptr;
}
}
return NULL;
}
/** 製品パターンIDから目的の製品のInit関数を呼び出す */
int configureProduct(int productId){
struct Product *targetProductPtr = findProduct(productId);
if(targetProductPtr == NULL){
return RESULT_CODE_FAILURE;
}
targetProductPtr->init();
targetProductPtr->read();
targetProductPtr->write();
return RESULT_CODE_SUCCESS;
};
int main(){
int resultCode = configureProduct(PRODUCT_ID);
// ここらへんはどうしたら良いのかわからん
if(resultCode != RESULT_CODE_SUCCESS){
return RESULT_CODE_FAILURE;
}
return RESULT_CODE_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment