unable to test bool output from c function

61 views Asked by At

I`m trying to check the result of a call toGetConsoleScreenBufferInfo that returns a bool

const c = @cImport({
    @cInclude("Windows.h");
});

const TermSz = struct { height: usize, width: usize };
var term_sz: TermSz = .{ .height = 0, .width = 0 };
//get terminal size given a tk  ty
pub fn getTermSz() !TermSz {
    var csbi: c.CONSOLE_SCREEN_BUFFER_INFO = undefined;

    const stdoutHandle = c.GetStdHandle(c.STD_OUTPUT_HANDLE);
    if (stdoutHandle == c.INVALID_HANDLE_VALUE) {
        return error.FailedToGetStdoutHandle;
    }
    if (c.GetConsoleScreenBufferInfo(stdoutHandle, &csbi)) {
        return TermSz{
            .width = @as(usize, csbi.dwSize.X),
            .height = @as(usize, csbi.dwSize.Y),
        };
    } else {
        return error.FailedToGetConsoleScreenBufferInfo;
    }
}

resulted in

main.zig:57:37: error: expected type 'bool', found 'c_int'
    if (c.GetConsoleScreenBufferInfo(stdoutHandle, &csbi))

I tried different ways of casting to int, but none of them were able to run, here are all of the combinations + compiler output. Running zig 0.11.0 on windows 10.

main.zig:59:59: error: expected type 'usize', found 'c_short'
    if (c.GetConsoleScreenBufferInfo(stdoutHandle, &csbi) != 0) {

this returns the same error for all int types (u8, u16, u32, i8, i16, i32)

 var result: usize = @intCast(c.GetConsoleScreenBufferInfo(stdoutHandle, &csbi));
    if (result != 0) {


main.zig:59:16: error: expected type 'usize', found 'c_short'
    if (result != 0) {
        ~~~~~~~^~~~
main.zig:59:16: note: unsigned 64-bit int cannot represent all possible signed 16-bit values

this returns the same error as version above

var zero: i16 = @intCast(0);
var result: i16 = @intCast(c.GetConsoleScreenBufferInfo(stdoutHandle, &csbi));
if (result != zero) {
1

There are 1 answers

6
sigod On

You have more than one problem in your code.

First, as you already realized, GetConsoleScreenBufferInfo does not return bool. Comparing the result to 0 is enough.

Second, @as does not cast types, it does type coercion. You need to use @intCast for width and height:

TermSz{
    .width = @intCast(csbi.dwSize.X),
    .height = @intCast(csbi.dwSize.Y),
}