Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That's all fine, but you cannot have nicely behaved stack allocated structs and use the data hiding method outlined in that blog post, which I think is a pretty big caveat


Yes, allowing clients to control allocation of a struct is a crucial feature of any C API, especially if it's going to be used on embedded targets where heap is unavailable or restricted.

The pattern I like to use for this is to expose class definitions, and declare each field with an underscore suffix to indicate it's private.

  typedef struct Foo {
    int x_; // implementation detail. don't touch.
  } Foo;
Another pattern I've seen for this is to use truly opaque structs of byte arrays, that are then typecast into the proper struct in the implementation.

  // foo.h
  #define FOO_SIZE_ 4
  #define FOO_ALIGN_ 4
  typedef struct Foo {
    _Alignas(FOO_ALIGN_) char impl_[FOO_SIZE_];
  } Foo;

  // foo.c
  #include "foo.h"
  typedef struct FooImpl {
    int x;
  } FooImpl;
  _Static_assert(FOO_SIZE_ == sizeof(FooImpl), "");
  _Static_assert(FOO_ALIGN_ == _Alignof(FooImpl), "");

  void Foo_bar(Foo const* self_opaque) {
    FooImpl const* self = (FooImpl)self_opaque;
    ...
  }
I'm not a big fan of this approach, but it does protect your clients against themselves.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: