我想隐藏库用户的内部类型。目前我有这样的事情:
foo.h中
typedef struct public{ uint16 a; // … unsigned char internals [4];} public_type; …
你可以在foo.h做:
typedef struct internals_type; typedef struct { uint16 a; internals_type* internals; } public_type
包含foo.h就足以让你的用户编译,而不知道究竟是什么内部 internals_type 。
internals_type
通常你使用 void* 隐藏您的实施,例如
void*
void *create_foo(int param1, int param2); void print_foo(void* foo); int operate_on_foo(void* foo);
所以你“投”了 void* 在你的函数中你的内部类型。
这样做的缺点是,编译器无法帮助您处理类型,例如:库的用户可以使用 int* 并将其传递给您的函数,编译器将接受它。当您使用实际类型时,编译器会抱怨。
int*