不透明的 C 结构:声明它们的各种方法 [英] Opaque C structs: various ways to declare them
问题描述
我已经看到以下两种在 C API 中声明不透明类型的风格.在 C 中声明不透明结构/指针的各种方法是什么?使用一种风格比使用另一种风格有什么明显的优势吗?
I've seen both of the following two styles of declaring opaque types in C APIs. What are the various ways to declare opaque structs/pointers in C? Is there any clear advantage to using one style over the other?
// foo.h
typedef struct foo * fooRef;
void doStuff(fooRef f);
// foo.c
struct foo {
int x;
int y;
};
选项 2
// foo.h
typedef struct _foo foo;
void doStuff(foo *f);
// foo.c
struct _foo {
int x;
int y;
};
推荐答案
我的投票是支持 mouviciel 发布然后删除的第三个选项:
My vote is for the third option that mouviciel posted then deleted:
我见过第三种方式:
// foo.h
struct foo;
void doStuff(struct foo *f);
// foo.c
struct foo {
int x;
int y;
};
如果你实在受不了输入struct
关键字,typedef struct foo foo;
(注意:去掉无用和有问题的下划线)是可以接受的.但是无论你做什么,永远不要使用typedef
来定义指针类型的名称.它隐藏了一条极其重要的信息,即这种类型的变量引用了一个对象,只要你将它们传递给函数,就可以修改该对象,并且它可以处理不同限定的(例如,const
-qualified)指针的版本是一个主要的痛苦.
If you really can't stand typing the struct
keyword, typedef struct foo foo;
(note: get rid of the useless and problematic underscore) is acceptable. But whatever you do, never use typedef
to define names for pointer types. It hides the extremely important piece of information that variables of this type reference an object which could be modified whenever you pass them to functions, and it makes dealing with differently-qualified (for instance, const
-qualified) versions of the pointer a major pain.
这篇关于不透明的 C 结构:声明它们的各种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!