Re: Opaque pointers



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.

--
pete
.



Relevant Pages

  • Re: Opaque pointers
    ... pete wrote: ... extern T List_list (void *x, ... In your header file, you'd have something along the lines of: ... The actual definition of 'struct foo' goes in the source file: ...
    (comp.lang.c)
  • [S390] New header file ipl.h
    ... Setup.h has been misused for ipl related stuff in the past. ... which has to do with ipl and reipl to a new header file named ... void *addr) ... +extern u32 ipl_flags; ...
    (Linux-Kernel)
  • Re: Opaque pointers
    ... extern T List_list (void *x, ... typedef struct foo foo; ... The actual definition of 'struct foo' goes in the source file: ... The defintion of the stuct type needs to be in the header file. ...
    (comp.lang.c)
  • Re: [PATCH] Fix build failure in recent pm_prepare_* changes.
    ... These should be in a header file. ... +static inline void pm_restore_console ... static inline int software_suspend ... extern void disable_nonboot_cpus; ...
    (Linux-Kernel)
  • Re: Opaque pointers
    ... extern T List_append ... extern T List_list (void *x, ... The actual definition of 'struct foo' goes in the source file: ... The contents are hidden, ie opaque, from everything that merely includes foo.h - all you can do is pass pointers around. ...
    (comp.lang.c)