如何解决如何使用无效指针在结构中包装其他类型
今晚早些时候我有一个计划,现在变成了一片混乱……我认为我缺少一些基本概念。
这里是个主意: 我必须通过uart发送一些如下所示的内容:
rpmL.txt="10"
vbatt.txt="20.4"
info.txt="Low Temperature"
battIcon.pic='8'
足够简单,对吧?
现在,我有一堆不同的东西,都具有相同的格式,但是唯一改变的是:
rpmL,vbatt,etc.
txt
(可以是txt
或pic
)
10,20.4,Low Temperature,8
(可以是int或float或字符串或枚举...您将在下面看到该枚举)
所以,我的想法是,仅创建一个具有所有可以更改的所有类型的typedef的结构,然后再创建一个包含一堆此类typedef的“事物”的结构。
无论如何,这是代码,我只是想根据其类型以不同的方式增加内容:
screen.h
typedef enum _ScreenType{
T_INT,T_FLOAT,T_CHAR,T_TEMP_ICON,T_BATT_ICON
} ScreenType;
typedef enum _tempIcon{
TEMP_LOW = 0,TEMP_MED,TEMP_HIGH,//Add More Elements Up Here
TEMP_MAX_ELEMENTS
}TempIcon;
typedef enum _battIcon{
BATT_ZERO = 0,BATT_TWENTY_FIVE,BATT_FIFTY,BATT_SEVENTY_FIVE,BATT_FULL,//Add More Elements Up Here
BATT_MAX_ELEMENTS
}BattIcon;
// Jam everything together so we can just pass the memeber of the following struct to the LCD TX function
typedef struct _packedStringVars{
ScreenType ScreenType; // I think I need this to achieve some crude polymorphism later on...
void* var; //I think I should do this because this can be a float,int or char*...
char* label; //This is always a string...nothing special about this.
}packedStringVars;
typedef struct{
packedStringVars temp;
packedStringVars wattage;
packedStringVars battPercent;
packedStringVars rpmL;
packedStringVars rpmR;
packedStringVars vbat;
packedStringVars tempIcon;
packedStringVars battIcon;
}mainScreenVariables;
这是来源:
screen.c
#include "screen.h"
#include ..........Everything Else that You Would Expect.......
//This is where I'm trying to 'initialize' the values...I was doing *(int*) and *(float*),etc.,but that went nowhere...
mainScreenVariables screenData = {
.temp = {T_INT,"temp"},.wattage = {T_INT,"watts"},.rpmL = {T_INT,"rpmL"},.rpmR = {T_INT,"rpmR"},.vbat = {T_FLOAT,"vbat"},.tempIcon = {T_TEMP_ICON,(TempIcon*)TEMP_LOW,"p1"},.battIcon = {T_BATT_ICON,(BattIcon*)BATT_FULL,"battIcon"}
};
static void updateValues(void)
{
// As you can see,now i'm typecasting them as I'm using them,which feels all kinds of wrong and also,as it turns out,doesn't even work! surprise surprise....
*(int*)screenData.temp.var++;
*(int*)screenData.wattage.var++;
*(int*)screenData.battPercent.var++;
*(int*)screenData.rpmL.var++;
*(int*)screenData.rpmR.var++;
*(float*)screenData.vbat.var+=0.1;
*(TempIcon*)screenData.tempIcon.var++;
*(ScreenType*)screenData.battIcon.var++;
}
还有更多代码可确保枚举不会超出其范围,等等,但是实际上,我要做的只是设置此概念性的 object ,并将其发送到UART ,其功能签名如下所示:
void ForChristsSakesJustSendTheDamnString(screenData * dat);
我敢肯定,有一些更好的,惯用的方式可以做到这一点。这完全失控了,只是感觉错误。
谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。