编程小记:C/C++: typedef void *HANDLE

参考链接: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);
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微风❤水墨

你的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值