我正在为嵌入式设备开发“第一个”C 软件。
我想以oo风格编写代码,所以我开始使用结构。
typedef struct sDrawable {
Dimension size;
Point location;
struct sDrawable* parent;
bool repaint;
bool focused;
paintFunc paint;
} Drawable;
typedef struct sPanel {
Drawable drw;
struct sDrawable* child;
uint16_t bgColor;
} Panel;
我不能也不想使用 malloc,所以我寻找更好的方法来实例化我的结构。这可以接受吗?
Panel aPanel={0};
void Gui_newPanel(Panel* obj, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t bgColor) {
// Drw is a macro to cast to (Drawable*)
Drw(obj)->repaint = true;
Drw(obj)->parent= NULL;
Drw(obj)->paint = (paintFunc) &paintPanel;
Drw(obj)->location=(Point){x, y};
Drw(obj)->size=(Dimensione){w, h};
obj->child = NULL;
obj->bgColor = bgColor;
}
void Gui_init(){
Gui_newPanel(&aPanel, 0, 0, 100, 100, RED);
}
更新
在第一个中,我必须像Panel aPanel={0};
将其指针传递给 Gui_newPanel 函数一样初始化结构,或者我只能写Panel aPanel;
?我已经测试过并且两者都有效,但也许我只是不走运......
或者这是一个更好的方法?
Panel aPanel;
Panel Gui_newPanel(uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t bgColor) {
// Drw is a macro to cast to (Drawable*)
Panel obj;
Drw(&obj)->repaint = true;
Drw(&obj)->parent= NULL;
Drw(&obj)->paint = (paintFunc) &paintPanel;
Drw(&obj)->location = (Point){x, y};
Drw(&obj)->size = (Dimension){w, h};
obj.child = NULL;
obj.bgColor = bgColor;
return obj;
}
void Gui_init(){
aPanel=Gui_newPanel(0, 0, 100, 100, RED);
}
这些方法中哪一种更可取?
我对性能和内存使用特别感兴趣。
谢谢