在为嵌入式系统编程时,通常不允许使用malloc().大部分时间我都能够处理这个问题,但有一件事让我感到恼火:它使我无法使用所谓的"不透明类型"来启用数据隐藏.通常我会做这样的事情:
// In file module.h
typedef struct handle_t handle_t;
handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);
// In file module.c
struct handle_t {
int foo;
void *something;
int another_implementation_detail;
};
handle_t *create_handle() {
handle_t *handle = malloc(sizeof(struct handle_t));
// other initialization
return handle;
}
Run Code Online (Sandbox Code Playgroud)
你去:create_handle()执行malloc()来创建'实例'.通常用于防止必须使用malloc()的构造是更改create_handle()的原型,如下所示:
void create_handle(handle_t *handle);
Run Code Online (Sandbox Code Playgroud)
然后调用者可以这样创建句柄:
// In file caller.c
void i_am_the_caller() {
handle_t a_handle; // Allocate a handle on the stack instead of malloc()
create_handle(&a_handle);
// ... a_handle …Run Code Online (Sandbox Code Playgroud) 在问题中我们为什么要在C中经常输入一个结构?,放松回答:
在后一种情况下,您不能返回Point by值,因为它的声明对头文件的用户是隐藏的.例如,这是GTK +中广泛使用的技术.
如何完成声明隐藏?为什么我不能按值返回Point?
加:
我理解为什么我不能通过值返回结构,但是,仍然很难理解为什么我不能在我的函数中尊重这一点.即如果我的结构有名为y的成员,为什么我不能这样做?
pointer_to_struct->y = some_value; Run Code Online (Sandbox Code Playgroud)
我为什么要使用方法呢?(像Gtk +)
谢谢你们,再次为我糟糕的英语道歉.