Type ‣ Opaque ᴾᴴᴾ - chung-leong/zigar GitHub Wiki

JavaScript | PHP


An opaque is a notional type in the Zig language. It's used to create a pointer that points to "mystery" data, whose meaning is only known to the code that created it:

const std = @import("std");

const Context = struct {
    number1: i32,
    number2: i32,
    number3: i32,
};
const OpaquePtr = *align(@alignOf(Context)) opaque {};

pub fn startContext(allocator: std.mem.Allocator) !OpaquePtr {
    const ctx = try allocator.create(Context);
    ctx.* = .{ .number1 = 10, .number2 = 20, .number3 = 30 };
    return @ptrCast(ctx);
}

pub fn showContext(opaque_ptr: OpaquePtr) void {
    const ctx: *Context = @ptrCast(opaque_ptr);
    std.debug.print("{any}\n", .{ctx.*});
}
<?php

$m = zigar_use(__DIR__ . '/opaque-example-1.zig');

$ctx = $m->startContext();
print_r($ctx);
$m->showContext($ctx);
*O0 Object
(
)
.{ .number1 = 10, .number2 = 20, .number3 = 30 }

Casting to an opaque pointer is a way of hiding implementation details.


Types