Pointer Issue with Unit Test for Code that is Cross Compiled

I’ve been working on a zig project for an arm cortex microcontroller which has 32bit architecture. There are a couple places in my code where I use @intFromPtr to set the values of a u32. This is causing an issue with one of my unit tests as the tests are run on my PC which is a 64 bit machine.

os_task.zig:18:14: error: expected type ‘u32’, found ‘usize’
.stack_ptr = @intFromPtr(&config.stack[config.stack.len - 16]),
os_task.zig:18:14: note: unsigned 32-bit int cannot represent all possible unsigned 64-bit values

Since my PC is 64bit the pointer address can’t fit into a u32. Does anyone have thoughts about the best way to solve this conundrum? Is there a way to run zig test as 32bit on my 64bit machine?

The obvious fix would be to use usize, that’s why it exists, it’s the native size of a pointer on any platform. So it would still be a u32 on 32-bit systems.

You could use an @intCast to stuff a 64-bit pointer into a u32, but you shouldn’t, it will unpredictably panic when the pointer address doesn’t fit. @truncate wouldn’t panic but it’s unlikely the result would be correct.

Basically you want to use usize for any pointer casting.

1 Like