Skip to content

Use case: Ability to create global constructor/destructor functions #20382

@alexrp

Description

@alexrp

(Note: This is not a proposal at this stage; I know there's little desire for language proposals at this time. I just wanted to indicate that this is a use case where pure Zig is currently unable to replace C. This can evolve into a concrete proposal later.)

I have a C# library that effectively replaces System.Console and instead centers console interaction around a terminal (i.e. VT100+). Among other concerns, this requires some platform-specific code to configure the terminal - termios on Unix, Win32 console on Windows - and to restore its configuration on process exit.

That last part turns out to be quite tricky. It's basically not possible to do reliably from C#. So I ended up writing a dynamically-loaded helper library in C that abstracts away the platform-specific bits and also performs the terminal configuration. Here's how configuration restoration looks, using the GCC/Clang __attribute__((destructor)) feature:

https://github.com/vezel-dev/cathode/blob/6bd76d8836c1988d96c58283de037de63f5e8ab9/src/native/driver-unix.c#L39-L46

I'm compiling that library with zig cc right now, but I'd like to take the extra step and rewrite it in Zig. Unfortunately, it doesn't seem like Zig has the ability to express the constructor/destructor attributes right now.

To my knowledge, there is no other feature (whether it's atexit() or what have you) that is as reliable at running cleanup code as __attribute__((destructor)). And it really is important that this code runs: If the terminal is configured in raw mode and the C# application exits abnormally due to an unhandled exception, the terminal could be left in an unusable state if this destructor doesn't run.

Metadata

Metadata

Assignees

No one assigned

    Labels

    use caseDescribes a real use case that is difficult or impossible, but does not propose a solution.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions