指针
Zig 提供两种指针:单项指针和多项指针。
*T—— 恰好指向一个元素的单项指针。- 支持解引用语法:
ptr.* - 支持切片语法:
ptr[0..1] - 支持指针相减:
ptr - ptr
- 支持解引用语法:
[*]T—— 指向未知数量元素的多项指针。- 支持索引语法:
ptr[i] - 支持切片语法:
ptr[start..end]和ptr[start..] - 支持指针与整数的算术运算:
ptr + int、ptr - int - 支持指针相减:
ptr - ptr
T必须具有已知大小,因此不能是anyopaque或其他任何不透明类型。- 支持索引语法:
*[N]T—— 指向 N 个元素的指针,相当于指向数组的单项指针。- 支持索引语法:
array_ptr[i] - 支持切片语法:
array_ptr[start..end] - 支持 len 属性:
array_ptr.len - 支持指针相减:
array_ptr - array_ptr
- 支持索引语法:
[]T—— 切片,即包含一个[*]T类型指针和一个长度的胖指针。- 支持索引语法:
slice[i] - 支持切片语法:
slice[start..end] - 支持 len 属性:
slice.len
- 支持索引语法:
使用 &x 获取单项指针:
const expectEqual = @import("std").testing.expectEqual;
test "address of syntax" {
// 获取变量地址:
const x: i32 = 1234;
const x_ptr = &x;
// 对指针解引用:
try expectEqual(1234, x_ptr.*);
// 获取 const 变量的地址,得到的是常量单项指针。
try expectEqual(*const i32, @TypeOf(x_ptr));
// 若要修改值,需要获取可变变量的地址:
var y: i32 = 5678;
const y_ptr = &y;
try expectEqual(*i32, @TypeOf(y_ptr));
y_ptr.* += 1;
try expectEqual(5679, y_ptr.*);
}
test "pointer array access" {
// 获取单个元素的地址会得到
// 单项指针。此类指针
// 不支持指针算术运算。
var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
const ptr = &array[2];
try expectEqual(*u8, @TypeOf(ptr));
try expectEqual(3, array[2]);
ptr.* += 1;
try expectEqual(4, array[2]);
}
test "slice syntax" {
// 获取指向变量的指针:
var x: i32 = 1234;
const x_ptr = &x;
// 使用切片语法转换为数组指针:
const x_array_ptr = x_ptr[0..1];
try expectEqual(*[1]i32, @TypeOf(x_array_ptr));
// 强制转换为多项指针:
const x_many_ptr: [*]i32 = x_array_ptr;
try expectEqual(1234, x_many_ptr[0]);
}$ zig test test_single_item_pointer.zig
1/3 test_single_item_pointer.test.address of syntax...OK
2/3 test_single_item_pointer.test.pointer array access...OK
3/3 test_single_item_pointer.test.slice syntax...OK
All 3 tests passed.
Zig 支持指针算术运算。最好将指针赋值给 [*]T 后递增该变量。例如,直接递增切片中的指针会破坏切片状态。
const expectEqual = @import("std").testing.expectEqual;
test "pointer arithmetic with many-item pointer" {
const array = [_]i32{ 1, 2, 3, 4 };
var ptr: [*]const i32 = &array;
try expectEqual(1, ptr[0]);
ptr += 1;
try expectEqual(2, ptr[0]);
// 对多项指针切片时省略结束位置,等价于
// 指针算术运算:`ptr[start..] == ptr + start`
try expectEqual(ptr[1..], ptr + 1);
// 除切片外,任意两个指针均支持按元素大小计算的指针相减
try expectEqual(1, &ptr[1] - &ptr[0]);
}
test "pointer arithmetic with slices" {
var array = [_]i32{ 1, 2, 3, 4 };
var length: usize = 0; // 使用 var 使其仅在运行时已知
_ = &length; // 抑制“变量从未被修改”的错误
var slice = array[length..array.len];
try expectEqual(1, slice[0]);
try expectEqual(4, slice.len);
slice.ptr += 1;
// 由于 len 未更新,切片现在处于无效状态
try expectEqual(2, slice[0]);
try expectEqual(4, slice.len);
}$ zig test test_pointer_arithmetic.zig
1/2 test_pointer_arithmetic.test.pointer arithmetic with many-item pointer...OK
2/2 test_pointer_arithmetic.test.pointer arithmetic with slices...OK
All 2 tests passed.
在 Zig 中,通常优先使用切片而非哨兵终止指针。可以使用切片语法将数组或指针转换为切片。
切片具有边界检查,因此能够防止这类非法行为。这也是优先使用切片而非指针的原因之一。
const expectEqual = @import("std").testing.expectEqual;
test "pointer slicing" {
var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var start: usize = 2; // 使用 var 使其仅在运行时已知
_ = &start; // 抑制“变量从未被修改”的错误
const slice = array[start..4];
try expectEqual(2, slice.len);
try expectEqual(4, array[3]);
slice[1] += 1;
try expectEqual(5, array[3]);
}$ zig test test_slice_bounds.zig
1/1 test_slice_bounds.test.pointer slicing...OK
All 1 tests passed.
只要代码不依赖未定义的内存布局,指针在编译期也可以使用:
const expectEqual = @import("std").testing.expectEqual;
test "comptime pointers" {
comptime {
var x: i32 = 1;
const ptr = &x;
ptr.* += 1;
x += 1;
try expectEqual(3, ptr.*);
}
}$ zig test test_comptime_pointers.zig
1/1 test_comptime_pointers.test.comptime pointers...OK
All 1 tests passed.
使用 @ptrFromInt 将整数地址转换为指针,使用 @intFromPtr 将指针转换为整数:
const expectEqual = @import("std").testing.expectEqual;
test "@intFromPtr and @ptrFromInt" {
const ptr: *i32 = @ptrFromInt(0xdeadbee0);
const addr = @intFromPtr(ptr);
try expectEqual(usize, @TypeOf(addr));
try expectEqual(0xdeadbee0, addr);
}$ zig test test_integer_pointer_conversion.zig
1/1 test_integer_pointer_conversion.test.@intFromPtr and @ptrFromInt...OK
All 1 tests passed.
只要从不解引用该指针,Zig 就能在编译期代码中保留内存地址:
const expectEqual = @import("std").testing.expectEqual;
test "comptime @ptrFromInt" {
comptime {
// Zig 可以在编译时执行此操作,前提是
// 从不对 ptr 解引用。
const ptr: *i32 = @ptrFromInt(0xdeadbee0);
const addr = @intFromPtr(ptr);
try expectEqual(usize, @TypeOf(addr));
try expectEqual(0xdeadbee0, addr);
}
}$ zig test test_comptime_pointer_conversion.zig
1/1 test_comptime_pointer_conversion.test.comptime @ptrFromInt...OK
All 1 tests passed.
@ptrCast 将指针的元素类型转换为另一种类型。通过新指针读写时,可能造成无法检测的非法行为。如果可以,通常应优先选择其他类型转换,而非 @ptrCast。
const std = @import("std");
const native_endian = @import("builtin").target.cpu.arch.endian();
const expectEqual = std.testing.expectEqual;
test "pointer casting" {
const bytes: [4]u8 align(@alignOf(u32)) = .{ 0x10, 0x20, 0x30, 0x40 };
const u32_ptr: *const u32 = @ptrCast(&bytes);
// 因为直接重新解释内存字节,从 `u32_ptr` 读取的
// `u32` 值取决于目标平台的字节序:
switch (native_endian) {
.little => try expectEqual(0x40302010, u32_ptr.*),
.big => try expectEqual(0x10203040, u32_ptr.*),
}
// 若要重新解释 `bytes` 的逻辑位表示,
// 且不依赖目标字节序,应使用 `@bitCast`,它始终将
// 位置更靠前的数组元素放入更低的有效位:
try expectEqual(0x40302010, @as(u32, @bitCast(bytes)));
}
test "pointer child type" {
// 指针类型的 `child` 字段表示其指向的类型。
try expectEqual(u32, @typeInfo(*u32).pointer.child);
}$ zig test test_pointer_casting.zig
1/2 test_pointer_casting.test.pointer casting...OK
2/2 test_pointer_casting.test.pointer child type...OK
All 2 tests passed.
另见:
volatile
默认假设内存读取和写入没有副作用。如果某次读写应该有副作用,例如内存映射输入输出(MMIO),则使用 volatile。在以下代码中,带 mmio_ptr 的所有读写都保证发生,并且与源码顺序一致:
const expectEqual = @import("std").testing.expectEqual;
test "volatile" {
const mmio_ptr: *volatile u8 = @ptrFromInt(0x12345678);
try expectEqual(*volatile u8, @TypeOf(mmio_ptr));
}$ zig test test_volatile.zig
1/1 test_volatile.test.volatile...OK
All 1 tests passed.
注意,volatile 与并发和原子操作无关。如果某段代码将 volatile 用于内存映射输入输出之外的场景,那很可能是程序错误。
对齐
每种类型都具有对齐要求,其值是一个字节数。该类型的值从内存读取或写入内存时,内存地址必须能够被该数整除。可以使用 @alignOf 查询任意类型的对齐要求。
对齐取决于 CPU 架构,但始终是二的幂,且小于 1 << 29。
指针类型可以显式指定以字节计的对齐要求。如果未指定,默认与其底层类型的对齐要求相同。
const std = @import("std");
const builtin = @import("builtin");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "variable alignment" {
var x: i32 = 1234;
try expectEqual(*i32, @TypeOf(&x));
try expect(@intFromPtr(&x) % @alignOf(i32) == 0);
// 隐式对齐的指针可以强制转换为显式对齐的指针,
// 对齐值等于底层类型 `i32` 的对齐要求:
const ptr: *align(@alignOf(i32)) i32 = &x;
try expectEqual(1234, ptr.*);
}$ zig test test_variable_alignment.zig
1/1 test_variable_alignment.test.variable alignment...OK
All 1 tests passed.
类似于 *i32 可以强制转换为 *const i32,具有更大对齐值的指针也可以隐式转换为更小对齐值的指针,反之则不允许。
可以为变量和函数指定对齐要求,指向它们的指针会获得所指定的对齐要求:
const expectEqual = @import("std").testing.expectEqual;
var foo: u8 align(4) = 100;
test "global variable alignment" {
try expectEqual(4, @typeInfo(@TypeOf(&foo)).pointer.attrs.@"align");
try expectEqual(*align(4) u8, @TypeOf(&foo));
const as_pointer_to_array: *align(4) [1]u8 = &foo;
const as_slice: []align(4) u8 = as_pointer_to_array;
const as_unaligned_slice: []u8 = as_slice;
try expectEqual(100, as_unaligned_slice[0]);
}
fn derp() align(@sizeOf(usize) * 2) i32 {
return 1234;
}
fn noop1() align(1) void {}
fn noop4() align(4) void {}
test "function alignment" {
try expectEqual(1234, derp());
try expectEqual(fn () i32, @TypeOf(derp));
try expectEqual(*align(@sizeOf(usize) * 2) const fn () i32, @TypeOf(&derp));
noop1();
try expectEqual(fn () void, @TypeOf(noop1));
try expectEqual(*align(1) const fn () void, @TypeOf(&noop1));
noop4();
try expectEqual(fn () void, @TypeOf(noop4));
try expectEqual(*align(4) const fn () void, @TypeOf(&noop4));
}$ zig test test_variable_func_alignment.zig
1/2 test_variable_func_alignment.test.global variable alignment...OK
2/2 test_variable_func_alignment.test.function alignment...OK
All 2 tests passed.
如果指针或切片声明的对齐值较小,但你知道实际满足更大的对齐要求,可以使用 @alignCast 将其转换为对齐要求更高的指针。它在运行时不做任何操作,但会插入安全检查:
const std = @import("std");
test "pointer alignment safety" {
var array align(4) = [_]u32{ 0x11111111, 0x11111111 };
const bytes = std.mem.sliceAsBytes(array[0..]);
try std.testing.expectEqual(0x11111111, foo(bytes));
}
fn foo(bytes: []u8) u32 {
const slice4 = bytes[1..5];
const int_slice = std.mem.bytesAsSlice(u32, @as([]align(4) u8, @alignCast(slice4)));
return int_slice[0];
}$ zig test test_incorrect_pointer_alignment.zig
1/1 test_incorrect_pointer_alignment.test.pointer alignment safety...thread 701624 panic: incorrect alignment
/home/andy/src/zig/doc/langref/test_incorrect_pointer_alignment.zig:10:68: 0x124c7f6 in foo (test_incorrect_pointer_alignment.zig)
const int_slice = std.mem.bytesAsSlice(u32, @as([]align(4) u8, @alignCast(slice4)));
^
/home/andy/src/zig/doc/langref/test_incorrect_pointer_alignment.zig:6:48: 0x124c62e in test.pointer alignment safety (test_incorrect_pointer_alignment.zig)
try std.testing.expectEqual(0x11111111, foo(bytes));
^
/home/andy/src/zig/lib/compiler/test_runner.zig:295:25: 0x1200951 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/andy/src/zig/lib/compiler/test_runner.zig:74:28: 0x1200132 in main (test_runner.zig)
return mainTerminal(init);
^
/home/andy/src/zig/lib/std/start.zig:789:88: 0x11fc8cf in callMain (std.zig)
if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11fc2b1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
error: the following test command terminated with signal ABRT:
/home/andy/src/zig/.zig-cache/o/5590f74b0012b309979410fad799928d/test --seed=0x555ce0ab
allowzero
此指针属性允许指针的地址为零。只有在地址零可被映射的独立环境操作系统目标上才需要它。如果要表示空指针,请改用可选指针。具有 allowzero 属性的可选指针与普通指针的大小不同。在此示例中,如果指针没有 allowzero 属性,就会触发指针转换产生无效空值的 panic:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "allowzero" {
var zero: usize = 0; // 使用 var 使其仅在运行时已知
_ = &zero; // 抑制“变量从未被修改”的错误
const ptr: *allowzero i32 = @ptrFromInt(zero);
try expectEqual(0, @intFromPtr(ptr));
}$ zig test test_allowzero.zig
1/1 test_allowzero.test.allowzero...OK
All 1 tests passed.
哨兵终止指针
语法 [*:x]T 表示长度由哨兵值决定的指针。这能防止缓冲区溢出和越界读取。
const std = @import("std");
// 也可以使用 `std.c.printf`。
pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
pub fn main() anyerror!void {
_ = printf("Hello, world!\n"); // 正确
const msg = "Hello, world!\n";
const non_null_terminated_msg: [msg.len]u8 = msg.*;
_ = printf(&non_null_terminated_msg);
}$ zig build-exe sentinel-terminated_pointer.zig -lc
/home/andy/src/zig/doc/langref/sentinel-terminated_pointer.zig:11:16: error: expected type '[*:0]const u8', found '*const [14]u8'
_ = printf(&non_null_terminated_msg);
^~~~~~~~~~~~~~~~~~~~~~~~
/home/andy/src/zig/doc/langref/sentinel-terminated_pointer.zig:11:16: note: destination pointer requires '0' sentinel
/home/andy/src/zig/doc/langref/sentinel-terminated_pointer.zig:4:34: note: parameter type declared here
pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
^~~~~~~~~~~~~
referenced by:
callMain [inlined]: /home/andy/src/zig/lib/std/start.zig:788:64
callMainWithArgs [inlined]: /home/andy/src/zig/lib/std/start.zig:729:20
main: /home/andy/src/zig/lib/std/start.zig:754:28
1 reference(s) hidden; use '-freference-trace=4' to see all references
另见: