Created
April 9, 2019 10:51
-
-
Save ljmccarthy/4f372f060d2d2e11b594ad9188fd4720 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
use std.os.windows; | |
pub extern "kernel32" stdcallcc fn GetCommandLineW() LPWSTR; | |
pub extern "kernel32" stdcallcc fn LocalFree(hMem: *c_void) ?*c_void; | |
pub extern "shell32" stdcallcc fn CommandLineToArgvW(lpCmdLine: LPCWSTR, out_pNumArgs: *c_int) ?[*]LPWSTR; | |
fn getArgs(allocator: *std.mem.Allocator) ![][]u8 { | |
var numArgs: c_int = undefined; | |
var args = CommandLineToArgvW(GetCommandLineW(), &numArgs) orelse return error.OutOfMemory; | |
defer _ = LocalFree(@ptrCast(*c_void, args)); | |
var argsOut = try allocator.alloc([]u8, @intCast(usize, numArgs)); | |
errdefer allocator.free(argsOut); | |
var i: c_int = 0; | |
while (i < numArgs) : (i += 1) { | |
var argNum = @intCast(usize, i); | |
var argLen = std.mem.len(u16, args[argNum]); | |
argsOut[argNum] = std.unicode.utf16leToUtf8Alloc(allocator, args[argNum][0..argLen]) catch |err| { | |
for (argsOut[0 .. argNum - 1]) |allocatedArg| { | |
allocator.free(allocatedArg); | |
} | |
return err; | |
}; | |
} | |
return argsOut; | |
} | |
pub fn main() !void { | |
const stdout = try std.io.getStdOut(); | |
var direct_allocator = std.heap.DirectAllocator.init(); | |
defer direct_allocator.deinit(); | |
var arena = std.heap.ArenaAllocator.init(&direct_allocator.allocator); | |
defer arena.deinit(); | |
for (try getArgs(&arena.allocator)) |arg| { | |
try stdout.write(arg); | |
try stdout.write("\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment