Home > Software engineering >  Is there a way to force alignment to match between structures?
Is there a way to force alignment to match between structures?

Time:02-04

I'm trying to correctly implement an opaque pointer (aka handle) for library users to interact with my library without knowing internal details.

The setup is roughly like so:

typedef MyAlign double; // largest data type

struct MyImplementation {
  int a;
  char b[3];
  double c;
  char d[5];
};

struct MyHandle {
  char __private[sizeof(struct MyImplementation) - sizeof(MyAlign)];
  MyAlign __align;
};

// Some static asserts about size and alignment...

My question is, how can I be sure the MyHandle has the same alignment when larger types are added to the original structure (eg another structure)? Ideally I'd want the build to fail whenever these sorts of assumption breaking changes are made.

CodePudding user response:

One normally use pointers for opaque types.

foo.h:

// Incomplete struct as an opaque type.
// You could also use `typedef struct Foo *Foo;`
// (with the appropriate changes to the prototypes).
typedef struct Foo Foo;

Foo *Foo_new( ... );
void Foo_delete( Foo * );

void Foo_method1( Foo *, ... );
void Foo_method2( Foo *, ... );
...

foo.c:

struct Foo {
   ...
};

Foo *Foo_new( ... ) { ... }
void Foo_delete( Foo *foo ) { ... }

void Foo_method1( Foo *foo, ... ) { ... }
void Foo_method2( Foo *foo, ... ) { ... }
...

Foo_new is aware of the implementation, and thus will always return a properly-aligned pointer.

  • Related