bytecodealliance / wasmtime

A fast and secure runtime for WebAssembly
https://wasmtime.dev/
Apache License 2.0
14.87k stars 1.24k forks source link

Storing references/lifetimes in preview2 tables #7692

Open MendyBerger opened 7 months ago

MendyBerger commented 7 months ago

What's the proper way to store references from one value to another in tables?

Consider the following code, how can I store both the parent and child in a table? Could that be done without unsafe code?

struct Parent {
    val: bool
}

impl Parent {
    pub fn get_child<'a>(&'a self) -> Child<'a> {
        Child {
            val: &self.val
        }
    }
}

struct Child<'a> {
    val: &'a bool,
}

fn main() {
    let mut table = wasmtime_wasi::preview2::Table::new();

    let parent = Parent {
        val: true,
    };
    let child = parent.get_child();

    let parent = table.push(parent).unwrap();

    // can this be done somehow?
    table.push_child(child, &parent);
}
alexcrichton commented 7 months ago

This unfortunately cannot be done at this time. Usingpush_child you should be able to store indexes to other items, however (rather than references).