Edward Rutherford <> wrote:
> I've got an opaque type encapsulated with a typedef, ie
> typedef struct my_obj *my_obj_handle;
> What I want is to define a function type that takes one of these
> handles in such a way that the function cant modify what's pointed to, in
> accordance with Data Hiding principals.
> If I do something like
> my_function(const my_obj_handle H)
> {
> *H = something;
> }
> then this will compile OK because the const applies to H not *H!
If you insist on using typedefs for pointers (frowned upon
by many people here, and they have their reasons) use two
typedefs, one just like your original one
> typedef struct my_obj *my_obj_handle;
and another
typedef const struct my_obj * my_const_obj_handle;
and declare your function to take an argument of the
second type:
void my_function( my_const obj_handle H );
That will keep the function from changing what 'H' is pointing
to as the following simple test program will show when you try
to compile it
----------------8<------------------------------
struct my_obj
{
int a;
};
typedef struct my_obj * my_obj_handle;
typedef const struct my_obj * my_const_obj_handle;
struct my_obj something = { 1 };
void my_function( my_const_obj_handle H )
{
*H = something;
}
int main( void )
{
struct my_obj x;
my_obj_handle y = &x;
my_function( y );
return 1;
}
----------------8<------------------------------
> Also if I swap the const to the right and have my_function(my_obj_handle
> const H) then it's still H that's constant and not *H!
Yes. You created a new type and that is made constant, not
what it may be pointing to. The way you seem to think about
it is that a typedef is nothing ,ore than a fancy kind of
macro (i.e. a textual replacement command) but that it isn't.
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://toerring.de