参考链接:https://stackoverflow.com/questions/22447153/what-does-typedef-void-key-type-mean-in-c
This is typically used in public header files. For the user of the API, key_type is an opaque pointer, or handle.
All you can do with key_type
is pass it to functions accepting a a key_type
.
Those functions then internally cast that argument from key_type
/ void*
to a pointer to a structure where their data is stored. This requires that the key_type
object is previously allocated by another function from the same API.
Basically, it's a mechanism of hiding the inner workings of a library from its users, to improve modularity.
通常在公共头文件中使用。对于API用户,key_type是不透明的指针或句柄。您只能使用key_type将其传递给接受key_type的函数。
然后,这些函数在内部将参数从key_type / void *强制转换为指向存储其数据的结构的指针。这要求key_type对象事先由同一API的另一个函数分配。
基本上,这是一种向用户隐藏库内部工作原理的机制,以提高模块化。
// Public api in a .h file
typedef void* xyz_key_type;
xyz_key_type xyz_init();
void xyz_print_data(xyz_key_type handle);
void xyz_close(xyz_key_type handle);
// Private implementation a the .c file
struct xyz_private_data {
int x, y, z;
};
xyz_key_type xyz_init() {
struct xyz_private_data *data = malloc(sizeof(xyz_private_data));
memset(data, 0, sizeof(*data));
return (xyz_key_type)(data);
}
void xyz_print_data(xyz_key_type handle) {
struct xyz_private_data *data = (struct xyz_private_data*)handle;
printf("x :%d, y: %d, z: %d\n", data->x, data->y, data->z);
}
void xyz_close(xyz_key_type handle) {
free(data);
}