Re: Opaque pointers
- From: pete <pfiland@xxxxxxxxxxxxxx>
- Date: Thu, 17 Aug 2006 11:29:42 GMT
pete wrote:
Richard Harnden wrote:
chankl wrote:
Can anyone explain what's an opaque pointer and how it's implemented in
C?
I read about this concept in the book "C interfaces and
implementations".
Here's an example from the book (list.h - available from the website):
#define T List_T
typedef struct T *T;
struct T {
T rest;
void *first;
};
extern T List_append (T list, T tail);
extern T List_copy (T list);
extern T List_list (void *x, ...);
.
.
and so on...
It seems the struct behind List_T is now hidden from the application
using these functions.The contents of List_T cannot be accessed (or
dereferenced?).
But I don't see why not. If I have access to the header file, wouldn't
I be able to dereference the contents of the structure? Or am I missing
the meaning of opaque?
Any answers is much appreciated.
In your header file, you'd have something along the lines of:
foo.h
-----
typedef struct foo foo;
foo *create_foo(void);
void destroy_foo(foo *ptr);
void use_foo(foo *ptr);
The actual definition of 'struct foo' goes in the source file:
foo.c
-----
struct foo
{
/* ... */
};
So that it's only foo.c that knows what the contents of a struct foo
are. The contents are hidden, ie opaque, from everything that merely
includes foo.h - all you can do is pass pointers around.
That's wrong.
The defintion of the stuct type needs to be in the header file.
Otherwise,
void destroy_foo(foo *ptr);
wouldn't mean anything in the header file.
In general, it's only object defintions and function definitions
that don't belong in header files.
Typedefs and enums are two kinds of definitions
that are typically OK in header files.
I'm not too familiar with inline functions.
I think they can go in header files too,
but I'm not sure.
--
pete
.
- References:
- Opaque pointers
- From: chankl
- Re: Opaque pointers
- From: Richard Harnden
- Re: Opaque pointers
- From: pete
- Opaque pointers
- Prev by Date: Re: Should attachments be accepted in comp.lang.c?
- Next by Date: Re: Opaque pointers
- Previous by thread: Re: Opaque pointers
- Next by thread: Re: Opaque pointers
- Index(es):
Relevant Pages
|