@ptrCast no longer takes type

I’ve updated my local zig to the latest and noticed that @ptrCast now takes a single argument and no longer takes the type to cast as and I’m struggling to find a solution.

I had the following for initializing a C sockaddr_can type, setting all fields to zero, and then setting up what I need:

const c = @cImport({
    @cInclude("linux/can.h");
});

// ....

       var s = std.os.socket(std.os.AF.CAN, std.os.SOCK.RAW, 1) catch |err| return err;
       var idx = std.c.if_nametoindex(name);
       var sa: c.sockaddr_can = undefined;
       @memset(@ptrCast([*]u8, &sa)[0..@sizeOf(c.sockaddr_can)], 0); // <-- the problem line
       sa.can_family = std.os.AF.CAN;
       sa.can_ifindex = idx;

After the change I thought I would need to change the line to this:

       @memset(@as([*]u8, @ptrCast(&sa)[0..@sizeOf(c.sockaddr_can)]), 0); // <-- the problem line

But that fails and I’m thinking there’s got to be a better solution to ensuring the memory behind ‘sa’ is zero’d/cleared.

Any suggestions?

Thanks.

std.mem.zeroes takes any type as input and returns zero-initialized memory.
var sa = std.mem.zeroes(c.sockaddr_can) might be all you need.

1 Like

I think the original problem was the end parentheses of @as. It should be:

@memset(@as([*]u8, @ptrCast(&sa))[0..@sizeOf(c.sockaddr_can)], 0);

After this accepted proposal is implemented you could do this:

@memset((&sa)[0..1], 0);
1 Like