組み込みシステム用にプログラミングする場合、malloc()は絶対に許可されないことがよくあります。ほとんどの場合、これに対処することはできますが、イライラすることが1つあります。それは、データの非表示を有効にするために、いわゆる「不透明(OPAQUE)型」を使用できないことです。通常、私は次のようなことをします:
// 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で静的グローバルを使用しないでください。複数のインスタンスを作成できる必要があります)。