Mapping a C enum to Error values

To integrate with C code I implement functions with C signature. The C library has an enum with error values and expects that one of them is returned. Like:

typedef enum {
    MYLIB_ERROR_OK = 0,
    MYLIB_ERROR_ILLEGAL_VALUE,
    MYLIB_ERROR_IO_ERROR
} MYLIB_ERROR;

Is it possible to map these values to Zig Error values after or with @cinclude? The goal would be to use Zig error handling with try and returning the mapped errors. This would make it way more easy to write Zig functions with C signature and therefore would improve integration with existing C code.

1 Like

There isn’t any syntax sugar to do this for you, but the mapping is straightforward to do.

However, an error-returning function (!something or !void) cannot be exported to C, because C has no notion of Zig error returns. These functions will simply be returning a MY_LIB_ERROR as a regular return value, so no mapping is needed.

Otherwise, mapping one of these values to Zig, is a straightforward, if verbose switch or table lookup (with the pain of maintenance if the external library is changing).

2 Likes

If the number of errors is small, manual translate them.

If the number of errors is big, refer to this pattern.

Related discussion

2 Likes