gpt4 book ai didi

c - 我将如何重构此 C 代码以消除重复

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:50 24 4
gpt4 key购买 nike

我正在为微 Controller 编写驱动程序以连接传感器。我使用的传感器是 MAG3110。我写了一个可以控制传感器上所有东西的驱动程序,但是有很多代码重复。四分之三的函数形式如下:

 uint8_t ReadWhoAmI(uint8_t *readPtr)
{
return MagReadByte(WHO_AM_I, readPtr);
}

uint8_t SetSingleMeasurmentMode()
{
uint8_t currentReg1Flags;
ReadCtrlReg1(&currentReg1Flags);

currentReg1Flags &= 0xFC;
currentReg1Flags |= CTRL_REG1_SINGLE_MEASURMENT;

return WriteCtrlReg1(currentReg1Flags);
}

如何概括这些功能?我知道在函数式编程中我会简单地参数化函数,但我不知道如何在 C 中应用类似的概念。

最佳答案

您可以通过使用以下方式获得 SetSingleMeasurmentMode 的通用版本:

uint8_t SetSingleMeasurmentModeGen(void (*ReadFunction)(uint8_t*),
void (*WriteFunction)(uint8_t))
{
uint8_t currentReg1Flags;
ReadFunction(&currentReg1Flags);

// Assuming this logic remains same.
currentReg1Flags &= 0xFC;
currentReg1Flags |= CTRL_REG1_SINGLE_MEASURMENT;

return WriteFunction(currentReg1Flags);
}

并使用:

uint8_t SetSingleMeasurmentMode()
{
return SetSingleMeasurmentModeGen(ReadCtrlReg1, WriteCtrlReg1);
}

如果更改标志值的逻辑不相同,则需要传递另一个函数。

uint8_t SetSingleMeasurmentModeGen(void (*ReadFunction)(uint8_t*),
uint8_t (*TransformFlag)(uint8_t),
void (*WriteFunction)(uint8_t))
{
uint8_t currentReg1Flags;
ReadFunction(&currentReg1Flags);
return WriteFunction(TransformFlag(currentReg1Flags));
}

uint8_t TransformFlag1(uint8_t flag)
{
flag &= 0xFC;
flag |= CTRL_REG1_SINGLE_MEASURMENT;
return flag;
}

uint8_t SetSingleMeasurmentMode()
{
return SetSingleMeasurmentModeGen(ReadCtrlReg1, TransformFlag1, WriteCtrlReg1);
}

关于c - 我将如何重构此 C 代码以消除重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28840657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com