callback.zig (1981B)
1 const std = @import("std"); 2 const Device = @import("device.zig").Device; 3 const StringView = @import("common.zig").StringView; 4 5 fn CallbackType1(comptime T: type) type { 6 const enum_type = switch (@typeInfo(T)) { 7 .@"fn" => |f| f.params[0].type.?, 8 else => unreachable, 9 }; 10 return fn (enum_type, StringView, ?*anyopaque) callconv(.C) void; 11 } 12 13 pub fn Callback1( 14 user_callback: anytype, 15 ) CallbackType1(@TypeOf(user_callback)) { 16 const enum_type = switch (@typeInfo(@TypeOf(user_callback))) { 17 .@"fn" => |f| f.params[0].type.?, 18 else => @compileError("callback must be a function"), 19 }; 20 return struct { 21 const callback = user_callback; 22 fn wrapped_callback( 23 enum_value: enum_type, 24 message: StringView, 25 userdata1: ?*anyopaque, 26 ) callconv(.C) void { 27 _ = userdata1; 28 callback(enum_value, message.toSlice()); 29 } 30 }.wrapped_callback; 31 } 32 33 fn DeviceCallbackType(comptime T: type) type { 34 const enum_type = switch (@typeInfo(T)) { 35 .@"fn" => |f| f.params[0].type.?, 36 else => unreachable, 37 }; 38 return fn (*const Device, enum_type, StringView, ?*anyopaque, ?*anyopaque) callconv(.C) void; 39 } 40 41 pub fn DeviceCallback( 42 user_callback: anytype, 43 ) DeviceCallbackType(@TypeOf(user_callback)) { 44 const enum_type = switch (@typeInfo(@TypeOf(user_callback))) { 45 .@"fn" => |f| f.params[0].type.?, 46 else => @compileError("callback must be a function"), 47 }; 48 return struct { 49 const callback = user_callback; 50 fn wrapped_callback( 51 device: *const Device, 52 enum_value: enum_type, 53 message: StringView, 54 userdata1: ?*anyopaque, 55 userdata2: ?*anyopaque, 56 ) callconv(.C) void { 57 _ = device; 58 _ = userdata1; 59 _ = userdata2; 60 callback(enum_value, message.toSlice()); 61 } 62 }.wrapped_callback; 63 }