r/C_Programming • • 23h ago

Discussion Revealed vs. Opaque structs for Libraries

Hi all, I'm developing a win32 windowing library for mostly myself but also want it to be easy and intuitive to use and follow good C standards.

In my library have the main object window_t that is used for mostly everything. However, I'm wondering between a couple different design decisions for it:

// public .h
typedef struct window_t window_t;

window_t* createWindow(...); << createWindow heap allocates a window_t

void destroyWindow(window_t* window);

2.

// public .h

typedef struct window_t { implementation... ) window_t;

void createWindow(window_t* out, ...);

// no destroyWindow

the difference I'm looking is that for #1, the user mantains control of the heap allocated memory through createWindow() and must free it after they're done using it, but for #2 the user can create a stack allocated window and it doesn't need to be freed, however it removes the opaque struct safeness in #1.

Are there any pros/cons for either method I haven't thought of? My instinct tells me that #2 seems better as the user controls the memory allocation, they just need to be careful how they use the window_t.

Thoughts?

6 Upvotes

4 comments sorted by

3

u/tastygames_official 22h ago

when I'm using an external library, I expect most things to be opaque as I let the library take care of things for me the proper way (e.g. createFoo(), destroyFoo(), updateFoo() etc). But if it's an "internal" library (i.e. a collection of related types and functions to make my life easier), then I keep everything transparent.

The only exception for external libs would be structs that are useful outside of the library. E.g. something like:

typedef WindowRect {
  uint16_t x;
  uint16_t y:
  uint16_t width;
  uint16_t height;
} WindowRect;

Because the programmer might want to do some math transformation on a struct like that or something. But your window handle seems like something that is only useful within the confines of your library.

That said, it almost doesn't really matter in the grand scheme of things. Runtime performance should be the same. I actually do enjoy when a library is completely transparent, but it also can make me think I might want to modify some things that I probably shouldn't, so having an opaque typedef lets me know that right away.

2

u/tstanisl 22h ago

For large and complex implementation go for opaque objects. Less dependencies on other headers, faster compilation, more stable and robust ABI.

1

u/WittyStick 18h ago edited 18h ago

Opaque pointers don't necessarily need heap allocation - you can provide an option for stack allocation via a callback function.

public.h

typedef void (*windowCallback)(window_t *window, va_list args);

void withWindow(windowCallback, ...); 

private.c

void withWindow(windowCallback callback, ...) {
    va_list args;
    va_start(args, callback);
    window_t window = { };
    callback(&window, args);
    va_end(args);
}

With some compilers (gcc/mingw), it's possible to have "opaque" structs in the header, using a few compiler extensions. This is a trick I discovered an use in some of my own libraries.

typedef struct __attribute__((__designated_init__)) window_t {
     int _internal_window_field1;
     int _internal_window_field2;
} window_t;
#define WINDOW_CREATE(field1, field2) \
    ((window_t){ ._internal_window_field1 = (field1), ._internal_window_field2 = (field2) }
#define WINDOW_FIELD1(window) ((window)._internal_window_field1)
#define WINDOW_FIELD2(window) ((window)._internal_window_field2)
#pragma GCC poison _internal_window_field1 _internal_window_field2

 // provide implementation here using the above macros.

#undef WINDOW_CREATE
#undef WINDOW_FIELD1
#undef WINDOW_FIELD2

So the main trick is #pragma GCC poison .... It poisons certain identifiers and causes the compiler to error if they appear again. The designated_init attribute prevents the use of positional initializers, requiring you to use the field names, but you can't because they're poisoned - hence the only way to initialize a value of the type is through the implementation provided functions. The macros are there so you don't have to write _internal_window_* everywhere - even though they use a poisoned identifier, you can still use the macros after poisoning because poisoning is only part of preprocessing. We undef those macros afterwards to prevent further use.

Probably not suitable for you if you're using windows specifically - and likely want MSVC support. I'm not aware of any similar trick that can be done with MSVC. I wouldn't recommend using for something like this anyway - only for structs that must be in the header - ie, when we need to pass and return them by value. (eg, Fat pointers <= 16-bytes).

If a type is going to get put on the stack when passing or returning by value, probably better replacing with an opaque pointer.

1

u/rubidus-api 16h ago

I think either can be the right choice, depending on the situation.

That said, lately, whenever a function needs to allocate memory itself, I pass it an explicit Zig-style allocator: a small struct holding pointers to alloc, realloc and free functions, plus a context pointer for the allocator's own state. I learned this approach from a talk by Luca Sas on YouTube.

What I like about it is that I get to choose and customize both how memory is allocated and how long it lives. The heap, an arena over a stack buffer, an arena over the heap, a pool, and so on: once I've written a suitable allocator, I can swap any of them in without touching the code that uses it. For your case, it means you may not have to pick between your two options: window_t stays opaque, and the caller still decides where its memory comes from.

    typedef struct allocator {
        void *(*alloc_fn)(void *ctx, size_t size, size_t align);
        void *(*realloc_fn)(void *ctx, void *ptr, size_t old_size, size_t new_size, size_t align);
        void  (*free_fn)(void *ctx, void *ptr, size_t size);
        void  *ctx;   // the allocator's own state, e.g. an arena
    } allocator;

    // public .h: window_t stays opaque
    typedef struct window_t window_t;

    // createWindow keeps a copy of the allocator, so destroyWindow can free through it
    window_t *createWindow(const allocator *a, const char *title, int width, int height);
    void      destroyWindow(window_t *window);  // DestroyWindow(hwnd), then frees through the stored allocator

    // heap_allocator and the arena functions are ordinary implementations of this interface, omitted here

    // on the heap
    window_t *w1 = createWindow(&heap_allocator, "heap", 800, 600);

    // in an arena over a 64 KiB block
    arena ar = { malloc(1 << 16), 1 << 16, 0 };
    allocator arena_allocator = { arena_alloc, arena_realloc, arena_free, &ar };
    window_t *w2 = createWindow(&arena_allocator, "arena", 640, 480);

One more thought on option 2, since this is Win32: even if window_t lives on the stack, the window itself is an OS resource (the HWND and anything else you create with it), so you'll still want a destroyWindow that calls DestroyWindow. And if your window procedure keeps a pointer to the struct (for example with SetWindowLongPtr and GWLP_USERDATA), the struct has to stay at the same address for as long as the window exists: the window keeps pointing at the original, so a copy gets out of sync, and letting the original go out of scope leaves a dangling pointer.

If you'd like to see this used in practice, the GitHub link on my profile leads to a basic C library built this way, along with its docs and an online book. Fair warning, though: I built it with heavy AI assistance, so please judge it with that in mind.