在为嵌入式系统编程时,通常绝对不允许使用 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;
}
你去吧: create_handle() 执行 malloc() 来创建一个“实例”。一个经常用来避免 malloc() 的结构是改变 create_handle() 的原型,如下所示:
void create_handle(handle_t *handle);
然后调用者可以这样创建句柄:
// 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 is ready to go!
}
但不幸的是这段代码显然是无效的,handle_t 的大小是未知的!
我从来没有真正找到以适当方式解决此问题的解决方案。我很想知道是否有人有这样做的正确方法,或者可能是一种完全不同的方法来启用 C 中的数据隐藏(当然,在 module.c 中不使用静态全局变量,必须能够创建多个实例)。