Expose only required information without including unnecessary header files

本小妞迷上赌 提交于 2019-11-29 16:09:40

The C standard allows a pointer to a struct to be converted to a pointer to its first member and back. So you can package the members you want to expose into a struct and publish that in a public header:

typedef struct
{
    int port;
    char platform_id[50];
} sfp_public_t;

In a private header, you would have:

typedef struct
{
    sfp_public_t public;
    sff_eeprom_t sff_type; 
    char status_str[50];
    sff_dom_t sff_dom; 
} sfp_info_t;

Given a pointer p to an sfp_info_t, you may convert it to a pointer to an sfp_public_t and pass it to other code. When you receive such a pointer from other code, you may convert it to a pointer to an sfp_info_t.

The other code will of course not know the true size of the object, so it cannot allocate new instances. Your API will need to provide supporting routines to allocate such objects.

A drawback is this requires you access the packaged members using p->public.name instead of p->name inside your code, although the code that receives the converted pointer can simply use p->name. I think you may be able to avoid that by using an anonymous struct member inside sfp_info_t. But an anonymous struct cannot be declared with a tag or a typename, so you need to repeat the declaration:

typedef struct
{
    struct
    {
        int port;
        char platform_id[50];
    };
    sff_eeprom_t sff_type; 
    char status_str[50];
    sff_dom_t sff_dom; 
} sfp_info_t;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!