Hacker News
points by smj-edison 1 day ago | 0 comments
I'm currently working on my own Zig project (an interpreter) and right now I'm working on designing a C interface for it. Seeing things mentioned like having objects as opaque handles, or enum-keyed getters and setters, made me think about how clunky my current API is, since I leak too many details to callers.

What really caught my attention was this: "So from the start, I took inspiration from C libraries I enjoyed working with and designed the API to have a strong, stable ABI that allows for future additions." What are good examples of this? I feel like I just don't have enough experience with well-designed C libraries to know what to look for.

[–] spacechild1 1 day ago
One example that comes to my mind is libopus: https://github.com/xiph/opus

If you have structs that might need to be extended, you can use "versioned structs". One popular technique is to include the struct size as the first field. The struct size is set to `offsetof(mystruct, lastmember) + sizeof(lastmember)` and the receiver of the struct can use this to check if a member exists. The ARA API is a good example: https://github.com/Celemony/ARA_API/blob/65ec5c43b943a48cb54...

[–] agosz 12 hours ago
If you do version and size as the first two fields, you're basically there to backwards and forwards compatibility. Callers can request the size of the struct, allocate a buffer, and read out the parts they need. They can also check specific versions for what they support and ignore newer versions.

It also helps if you only append to the end of the struct for newer fields.

[–] sigbottle 11 hours ago
My job requires thinking about things like this (well, more senior and experienced people actually drive the final decisions, but I still need to understand them). Seeing the level of rigor that went into the development of a stable C abi for this is insane, it hits on pretty much all the checklists (and more!) that we have internally.
[–] zem 21 hours ago
take a look at hpy, which is explicitly designing a better API for python C extensions. https://hpyproject.org/
[–] smj-edison 52 minutes ago
Ooh, will take a look at this, since it's directly applicable!