读书人

怎么隐藏自己定义的结构体使之不能直

发布时间: 2012-04-14 17:14:21 作者: rapoo

如何隐藏自己定义的结构体,使之不能直接访问成员变量?
如题,声明结构体,不让其他人通过头文件看到结构体具体定义,也不能直接访问结构体内的成员变量,只能通过自己提供的函数来获取成员变量的值。

新版的libpng有这样的介绍:

Portability Note

The libpng 1.5.x series continues the evolution of the libpng API, finally hiding the contents of the venerable and hoary png_struct and png_info data structures inside private (i.e., non-installed) header files. Instead of direct struct-access, applications should be using the various png_get_xxx() and png_set_xxx() accessor functions, which have existed for almost as long as libpng itself. (Apps that compiled against libpng 1.4 without warnings about deprecated features should happily compile against 1.5, too.)

之前的一个解码png图片的程序,使用老版本libpng可以编译通过,可是,自从安装新版本的libpng后,编译器会给出错误信息,无法编译通过,找遍了libpng的头文件,也没发现png_struct和png_info结构体的具体定义。


[解决办法]
直接把结构体定义写在.c文件中,然后自己typedef,然后在该.c文件中定义的该结构体类型的全局变量都用static类型
[解决办法]
别公开你的结构体定义不就得了。
[解决办法]
只提供指针(句柄)
[解决办法]

探讨

只提供指针(句柄)

[解决办法]
探讨
难道,
头文件只将void*指针typedef 成XXXX;
初始化用函数初始化,例如:XXX_init(xxxx);
获取结构体体成员变量时,直接get_XXXX(xxxx);获取。
修改结构体成员变量时,直接set_XXXX(xxxx);修改。

[解决办法]
如果楼主觉得写很多函数来设置成员变量麻烦的话,可以写一个xxx_ioctl函数来完成这些操作啊!

读书人网 >C语言

热点推荐