Вопрос

I am a little confused with the following line of code in C:

typedef void* key_type;

does it mean that key_type is a void pointer? I guess it's a more intuitive naming than void* in C programming. - Thank you

Это было полезно?

Решение

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.

Example:

// 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);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top