How to store a callback inside an string hash map

I am looking to build a plugin system based on JSON RPC 2.0

So when the server wants to call a method, I receive a notification with the name and parameter of the method.

The creator of the plugin adds this method, so my current design is to store a callback inside a StringHashMap where the key is the name of the function.

However, I came getting the following error that I am not able to resolve because I think it is more a conceptual problem that I have

This is the code

pub const Plugin = struct {
    const Self = @This();
    const CallbackFn = fn (std.mem.Allocator, *Self, *jsonrpc.Request) anyerror!jsonrpc.RPCResponse;
    const RPCInfo = struct {
        name: []const u8,
        description: []const u8,
    };

    rpc: ?jsonrpc.CLNUnix,
    rpcMethod: std.StringHashMap,
    rpcInfo: std.StringHashMap,
    onInit: ?CallbackFn,

    pub fn init(allocator: std.mem.Allocator) !Self {
        return Self{
            .rpcMethod = std.StringHashMap(CallbackFn).init(allocator),
            .rpcInfo = std.StringHashMap(RPCInfo).init(allocator),
        };
    }

    pub fn rpc(self: *Self) !jsonrpc.CLNUnix {
        return self.rpc orelse return error.NotFound;
    }

    // Add an RPC method
    pub fn addMethod(self: *Self, name: []const u8, description: []const u8, callback: CallbackFn) anyerror {
        try self.rpcMethod.put(name, callback);
        try self.rpcInfo.put(name, .{ .name = name, .description = description });
    }

src/plugin/plugin.zig:21:19: error: expected type 'type', found 'fn(comptime type) type'
    rpcMethod: std.StringHashMap,
               ~~~^~~~~~~~~~~~~~
referenced by:
    Self: src/plugin/plugin.zig:13:18
    init: src/plugin/plugin.zig:25:48
    remaining reference traces hidden; use '-freference-trace' to see all reference traces
src/plugin/plugin.zig:21:19: error: expected type 'type', found 'fn(comptime type) type'
    rpcMethod: std.StringHashMap,
               ~~~^~~~~~~~~~~~~~
referenced by:
    Self: src/plugin/plugin.zig:13:18
    init: src/plugin/plugin.zig:25:48
    remaining reference traces hidden; use '-freference-trace' to see all reference traces
make: *** [Makefile:4: build] Error 2

std.StringHashMap is a type function/generic type, which means you use it like rpcMethod: std.StringHashMap(CallbackFn).

Note also that
fn (std.mem.Allocator, *Self, *jsonrpc.Request) anyerror!jsonrpc.RPCResponse
is a comptime-only function body, so you won’t be able to store it in the hash map at runtime. You want to use
*const fn (std.mem.Allocator, *Self, *jsonrpc.Request) anyerror!jsonrpc.RPCResponse
which is a function pointer that can be used at runtime.

3 Likes