我是Rust的新手,这一点很明显。
基本上我有这样的场景,你可以在下面看到,我创建了一个新类型,它添加了一个闭包,但这个闭包需要访问尚未创建的数据。数据将在调用闭包时创建,但是当最初创建闭包时,数据还不可用。
处理问题的最好方法是什么?
我也很好奇,如果我的闭包不是一个闭包,而是我的实现中的一个私有函数,我如何访问这些数据?这个闭包/函数是一个来自WasmTime的回调,它需要一个显式的方法签名,这不允许我将$self添加到其中。那么,在函数参数中没有引用$self的情况下,如何获取实现的实例字段呢?
pub struct EmWasmNode {
wasmStore: Store<WasiCtx>,
wasmTable: Table,
}
impl EmWasmNode {
pub fn new(filePath: &str) -> Result<Self> {
let engine = Engine::default();
// let module = Module::from_file(&engine, "wasm/index.wast")?;
let module = Module::from_file(&engine, filePath)?;
let mut linker = Linker::new(&engine);
wasmtime_wasi::add_to_linker(&mut linker, |s| s)?;
let wasi = WasiCtxBuilder::new()
.inherit_stdio()
.inherit_args()?
.build();
let mut store = Store::new(&engine, wasi);
linker.func_wrap("env", "emscripten_set_main_loop", |p0: i32, p1: i32, p2: i32| {
println!("emscripten_set_main_loop {} {} {}", p0, p1, p2);
/*** How would I access wasmTable and wasmStore from here to execute more methods??? ***/
//let browserIterationFuncOption:Option<wasmtime::Val> = Self::wasmTable.get(&mut Self::wasmStore, p0 as u32);
// browserIterationFuncOption.unwrap().unwrap_funcref().call(&store, ());
})?;
let instance = linker.instantiate(&mut store, &module)?;
let table = instance
.get_export(&mut store, "__indirect_function_table")
.as_ref()
.and_then(extern_table)
.cloned();
let start = instance.get_typed_func::<(), (), _>(&mut store, "_start")?;
start.call(&mut store, ())?;
Ok(EmWasmNode {
wasmStore: store,
wasmTable: table.unwrap(),
})
}发布于 2021-11-26 08:13:09
你必须在之前实例化一个结构。我建议使用下面更简单的代码来了解我的想法。
struct Atype
{
name: String,
}
impl Atype
{
pub fn new() -> Self
{
Self{ name: String::from("zeppi")}
}
pub fn test(&self) -> ()
{
let func = | x | { println!("{} {}", &self.name, x);};
func(3)
}
}
fn main() {
let o = Atype::new();
o.test();
}https://stackoverflow.com/questions/70120881
复制相似问题