C中相同结构的两个名称

时间:2012-11-30 10:05:21

标签: c struct names

我想在我的.h / .c对中隐藏API的公共结构的本质,所以我只在.h中声明了typedef,并在.c中完成声明,如下所示:

foo.h中

typedef struct filters_s filters_t;

/* some public functions declaration using filters_t */
(...)

foo.c的

typedef struct filters_s filter_node_t;

struct filters_s
{
  filter_node_t *children[96];

  (...)
}

正如您所看到的,filters_s实际上是树的根节点,所以在内部,我使用filter_node_t但在外部,我不想暴露结构的“树”性质。 所以,我的“问题”是理想情况下我想为filter_node_s这样的结构设置另一个名称,但我不知道它是否可能。

1 个答案:

答案 0 :(得分:3)

如果要隐藏结构的实现,则需要一个指向结构的不透明指针。在那里,您可以将此指针传递给将获取或修改结构数据的函数。

声明将在* .h头文件中。定义将在* .c文件中。

* .h(头文件)中有类似的内容:

typedef struct tag_device device_t;

然后在* .c(实现文件)中:

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);
}

然后在您的* .c(驱动程序文件)

device_t *device = malloc(sizeof *device)

set_data(device, 1, "device02345");

我刚刚输入了这个,所以它可能不完美,因为我没有检查错误。完成后请务必记住释放内存。

希望这有帮助

相关问题