Skip to content
Chung Leong edited this page Apr 11, 2024 · 4 revisions

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

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.*});
}
import { showContext, startContext } from './opaque-example-1.zig';

const ctx = startContext();
console.log(ctx.valueOf());
showContext(ctx);
{}
opaque-example-1.Context{ .number1 = 10, .number2 = 20, .number3 = 30 }
Clone this wiki locally