#Get pointer from global variable and cast it to u64

1 messages · Page 1 of 1 (latest)

near viper
#

example:

var foo: [1024]u8 align(16) = undefined;
const fooptr = (&foo).ptr

if I try to int from ptr cast fooptr to u64, it gives an error "unable to evaluate comptime expression"

i wont be able to respond as im going to bed now, so please answer as best you can without asking me anything

next hatch
#

You don't show the code that yields the error. What you have is fine.

const std = @import("std");

var foo: [1024]u8 align(16) = undefined;
const fooptr = (&foo).ptr;

fn incr() void {
    foo[0] += 1;
}

test incr {
    foo[0] = 0;
    incr();
    incr();
    incr();
    try std.testing.expectEqual(3, fooptr[0]);
    std.debug.print(
        \\fooptr: {any}
        \\as u64: u8@{x}
        \\
    , .{ fooptr, @intFromPtr(fooptr) });
}
#

ah.

const std = @import("std");

var foo: [1024]u8 align(16) = undefined;
const fooptr = (&foo).ptr;
const foonum = @intFromPtr(fooptr); // error: unable to evaluate comptime expression

test {
    std.debug.print(
        \\fooptr: {any}
        \\as u64: u8@{x}
        \\foonum: u8@{x}
        \\
    , .{ fooptr, @intFromPtr(fooptr), foonum });
}
#

My reading: this requires foonum to have a definite u64 value, and it can't have one because the linker decides where that array will actually be located. I don't know this process well enough to say why fooptr is OK., but nothing at comptime is going to care about the exact numeric value of it.

#

You can @intFromPtr as needed, or make it a var and initialize it yourself.

const std = @import("std");

var foo: [1024]u8 align(16) = undefined;
const fooptr = (&foo).ptr;
var foonum: u64 = undefined;

test {
    foonum = @intFromPtr(fooptr);
    std.debug.print(
        \\fooptr: {any}
        \\as u64: u8@{x}
        \\foonum: u8@{x}
        \\
    , .{ fooptr, @intFromPtr(fooptr), foonum });
}