我正在为嵌入式设备开发“第一个”C软件。
我想用oo风格编写代码,所以我开始使用structs。
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);
}这些方法中哪一种更可取?
我对性能和内存使用特别感兴趣。
谢谢
发布于 2012-08-17 15:15:56
按值返回struct可能会导致复制结构成员的开销,尽管编译器通常会很聪明地对其进行优化。如果您关心开销,您应该分析这两种方法的相对性能。
此外,检查设备的目标编译器是否实际上能够支持返回的结构-一些非常老的编译器不支持返回或分配结构。
如果您有一个合理的现代编译器,您可能能够直接返回一个struct文本,这将是有效的:
return (Panel) {
.drw = {
.size = {w, h},
.location = {x, y},
// ...
},
.child = NULL,
.bgColor = bgColor
};https://stackoverflow.com/questions/12008336
复制相似问题