Cannot find std.os.windows.kernel32.SetConsoleOutputCP API to fix console garbled text issue

Hi everyone,

I’m trying to solve the console output garbled text problem on Windows. I found a potential solution in this thread: Crap - a fork of poop with macos support - #11 by squeek502 which mentions using std.os.windows.kernel32.SetConsoleOutputCP.

However, I’ve searched the standard library documentation thoroughly and cannot find this API anywhere. I’m using 0.16.

Could someone please tell me if this API has been moved, renamed, or if there’s an alternative way to set the console output code page in modern Zig? Any help would be greatly appreciated!

Thanks in advance.

It was removed from the standard library with the release of 0.16:

Any bindings that previously existed in the standard library can be placed in your project directly and they’ll work just the same. For SetConsoleOutputCP, sticking this in your project will work just fine:

extern "kernel32" fn SetConsoleOutputCP(wCodePageID: std.os.windows.UINT) callconv(.winapi) std.os.windows.BOOL;

(my personal preference is handwriting bindings for Windows APIs I need (based on the Win32 docs), but you can also check out zigwin32 if you want something more complete and auto-generated)

6 Likes

This is my first time using external functions. I just copied the code and don’t fully understand it yet.
The program runs correctly and the garbled text issue is fixed.
Here is my code:

const std = @import("std");
const builtin = @import("builtin");

extern "kernel32" fn SetConsoleOutputCP(wCodePageID: std.os.windows.UINT) callconv(.winapi) std.os.windows.BOOL;
extern "kernel32" fn SetConsoleCP(wCodePageID: std.os.windows.UINT) callconv(.winapi) std.os.windows.BOOL;

const CP_UTF8: c_uint = 65001;

pub fn initConsoleUTF8() void {
    if (builtin.os.tag == .windows) {
        _ = SetConsoleOutputCP(CP_UTF8);
        _ = SetConsoleCP(CP_UTF8);
    }
}

Thanks a lot for your help!