Reputation: 2216
I want to hide the nature of a public struct for an API inside my .h/.c couple, so I declare only the typedef in the .h and I complete the declaration in the .c like this:
typedef struct filters_s filters_t;
/* some public functions declaration using filters_t */
(...)
typedef struct filters_s filter_node_t;
struct filters_s
{
filter_node_t *children[96];
(...)
}
As you can see, filters_s is in fact the root node of a tree so internally, I'm using filter_node_t but externally, I don't want to expose the "tree" nature of the struct. So, my "problem" is that ideally I'd like to have also another name for the struct like filter_node_s, but I don't know if it's possible.
Upvotes: 1
Views: 1962
Reputation: 22696
If you want to hide the implementation of the structure then you need a opaque pointer to the structure. There you would pass this pointer to a function that will get or modify the data of the structure.
The declaration will be in the *.h header file. And the definition will be in the *.c file.
Something like this in the *.h (header file):
typedef struct tag_device device_t;
Then in the *.c (implementation file):
struct tag_device {
size_t id;
char *name;
};
void set_data(device_t *dev, size_t id, char *name)
{
dev->id = id;
dev->name = strdup(*name);
}
Then in your *.c (driver file)
device_t *device = malloc(sizeof *device)
set_data(device, 1, "device02345");
I have just typed this in, so it might not be perfect as I haven't checked for errors. Always remember to free memory after you finish with it.
Hope this helps
Upvotes: 3