注册 登录
编程论坛 C语言论坛

指针函数的结构体指针参数,如何优雅的适配不同结构体类型

szchen2018 发布于 2022-07-26 11:38, 1050 次点击
typedef struct
{
    uint8_t reg;        
    uint32_t data;
}COEFFICIENT_STRUCT;

typedef struct{
    uint8_t command;
    uint8_t param;
} cfg_reg;

typedef struct{
    uint8 Address;
    uint8 Top_data;
    uint8 Middle_data;
    uint8 Botton_data;
}RAM1_TAB;

typedef struct{
    BYTE Address;
    BYTE First_data;
    BYTE Top_data;
    BYTE Middle_data;
    BYTE Botton_data;
}RAM2_TAB;

上面四个结构体,会定义成结构体数组,现在每次选用不同的器件要打开相应宏定义,而且每增加一个器件又要增加宏定义、指针函数,很麻烦和不好看。
#define AMP_1
//#define AMP_2
//#define AMP_3
//#define AMP_4

#ifdef AMP_1
typedef int (*ampop_ctrl)( AmpList *pstAmpList, const COEFFICIENT_STRUCT *reg, int n);
#elif defined (AMP_2)
typedef int (*ampop_ctrl)( AmpList *pstAmpList, const cfg_reg *reg, int n);
#elif defined (AMP_3)
typedef int (*ampop_ctrl)( AmpList *pstAmpList, const RAM1_TAB *reg, int n);
#elif defined (AMP_4)
typedef int (*ampop_ctrl)( AmpList *pstAmpList, const RAM2_TAB *reg, int n);
#endif
3 回复
#2
rjsp2022-07-26 14:49
看不懂你的需求是什么,但如果是我来写的话,我会将

程序代码:
#if defined(AMP_1)
typedef struct {
    uint8_t reg;        
    uint32_t data;
} RAM_TAB;
#elif defined(AMP_2)
typedef struct {
    uint8_t command;
    uint8_t param;
} RAM_TAB;
#elif defined(AMP_3)
typedef struct {
    uint8 Address;
    uint8 Top_data;
    uint8 Middle_data;
    uint8 Botton_data;
} RAM_TAB;
#elif defined(AMP_4)
typedef struct {
    BYTE Address;
    BYTE First_data;
    BYTE Top_data;
    BYTE Middle_data;
    BYTE Botton_data;
} RAM_TAB;
#endif
typedef int (*ampop_ctrl)( AmpList *pstAmpList, const RAM_TAB *reg, int n );

存为一个头文件,比如 amp.h

然后在需要的地方
#define AMP_1
#incude "amp.h"
#3
szchen20182022-07-26 15:10
回复 2楼 rjsp
我的需求是typedef int (*ampop_ctrl)( AmpList *pstAmpList, const RAM_TAB *reg, int n )不用定义多个,结构体也不用定义多个,看来只能做到前者,感谢回答
#4
lwei2022-07-30 16:45
union能不能解决这个问题?
1