Returning error codes across the C ABI

Hi, I’m interfacing between Zig and C#. If Zig returns an error somewhere, I’d like to be able to convey that information to C#. Is there a better way of doing this, or should I just write a switch statement that returns an integer based on the error?

Thanks!

@intFromError and @errorFromInt may be what you are looking for, depending on what you want to do exactly.

Oh, I didn’t see @intFromError when I did my searching. Unfortunately it seems to be indexing the entire error set so it’s not particularly useful for this. (Tried printing out the values for my error set, FileNotFound had a value of 20, and then the rest started counting up from 52.)

what you want to do exactly

Return an error code so my C# code can display a message to the user. Something like this:

int status = ZigFunctions.DoThingThatCouldFail();

if (status != 0) // Display message to the user

Looks like my best bet here will be to hardcode some constants.

Right. From the langref:

It is generally recommended to avoid this cast, as the integer representation of an error is not stable across source code changes.

Since you probably want a stable ABI here, you’ll have to define your own error codes and do a switch.

5 Likes