xoa991x
xoa991x

Reputation: 69

Creating callback function with closure on a parameter, without "may outlive borrowed value" or "this closure implements `FnOnce`, not `Fn`"

I would like to create a callback function that has access to the argument instanceContext, but I am not sure how to fix the code. The failing code is instanceContext.instances.len().

I have tried using lifetimes, move, Rc, Arc, Box, RefCell, but nothing seems to work.

The goal is to have multiple Instances which will have callbacks that will make it possible for one Instance to call/modify another Instance, through the InstanceContext.

During my experimentation I've been getting the following errors:

use wasmtime::*;

struct InstanceContext {
    id: i32,
    instances: Vec<Instance>,
}

fn main() {
    let store = Store::new(&Engine::default());
    let mut instanceContext = InstanceContext { id: 5, instances: Vec::new() };
    let _callback = createCallback(&store, &mut instanceContext);
}

fn createCallback(store: &Store, instanceContext: &mut InstanceContext) -> wasmtime::Func {
    let f = Func::wrap(&store, || {
        println!("Number of instances: {}", instanceContext.instances.len());
    });
    f
}

Upvotes: 2

Views: 591

Answers (1)

Masklinn
Masklinn

Reputation: 42247

You don't provide the compiler error message or an actual reproduction case so it's hard to know whether the diagnostic achieved by just thinking about things is the correct one, but to me it looks like this would be the solution:

fn main() {
    let store = Store::new(&Engine::default());
    let mut instanceContext = Rc::new(RefCell::new(InstanceContext { id: 5, instances: Vec::new() }));
    let _callback = createCallback(&store, instanceContext.clone());
}

fn createCallback(store: &Store, instanceContext: Rc<RefCell<InstanceContext>>) -> wasmtime::Func {
    let f = Func::wrap(&store, move || {
        println!("Number of instances: {}", instanceContext.borrow().instances.len());
    });
    f
}

Upvotes: 2

Related Questions