John Doe
5/5/2011 6:40:00 AM
On Wed, 04 May 2011 09:47:13 -0700, dr.oktopus wrote:
> a proper way to implement an opaque type in c language is hide
> its implementation in .c files, and typedef a pointer to it in .h like
> this:
>
> typedef struct list_st *list;
>
> list new_list (void);
> ..
Arguably the "proper" way to do it would be to just declare the struct in
the header file:
struct list_st;
struct list_st *new_list(void);
..
Just because you can use a typedef, it doesn't mean that you should.
Forcing the user to write:
struct list_st *l = new_list();
means that anyone reading the code has a bit more information about what
is actually happening, while still preventing "illegal" access to the
structure's fields.
> However, I note that often this way is a little modified to
> keep out the pointer from the declaration of the new type
> (example from a stdio.h):
>
> typedef struct __iobuf *FILE;
Your example appears to contradict the point you're making.
FWIW, GNU libc uses:
typedef struct _IO_FILE FILE;
> Perhaps since C programmers want explicit pointers.
This particular case is dictated by the standard; the functions in
<stdio.h> use "FILE *".
> An opaque struct typedef'ed without a pointer could
> cost in terms of efficiency when passing/receiving
> to/from functions
If the structure is opaque, you cannot pass it by value or otherwise
create objects of that type (as opposed to a pointer to it), as the
compiler doesn't know its size. You'll get an "incomplete type" (or
similar) error if you try to do this.