Skip to content

Commit

Permalink
feat(api) Avoid using a closure to declare host function.
Browse files Browse the repository at this point in the history
Closures as host functions are going to be disabled for a moment in
Wasmer, see wasmerio/wasmer#1841. In the
`wasmer` Python package, we were passing a closure to
`Function::new_with_env`. In order to get a regular function, this
patch stores the previously captured varibles into the function
environment. The only concerned variable is `result_types`.
  • Loading branch information
Hywan committed Nov 27, 2020
1 parent 99bd88d commit e57f02d
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions packages/api/src/externals/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,19 +136,21 @@ impl Function {

struct Environment {
py_function: PyObject,
result_types: Vec<wasmer::Type>,
}

let environment = Environment {
py_function: py_function.to_object(py),
result_types: result_types.clone(),
};

let host_function = wasmer::Function::new_with_env(
store.inner(),
&wasmer::FunctionType::new(argument_types, result_types.clone()),
&wasmer::FunctionType::new(argument_types, result_types),
environment,
move |environment,
arguments: &[wasmer::Value]|
-> Result<Vec<wasmer::Value>, wasmer::RuntimeError> {
|environment,
arguments: &[wasmer::Value]|
-> Result<Vec<wasmer::Value>, wasmer::RuntimeError> {
let gil = Python::acquire_gil();
let py = gil.python();

Expand All @@ -162,7 +164,8 @@ impl Function {
wasmer::RuntimeError::new(io::Error::from(error).to_string())
})?;

let result_types = result_types.clone();
let result_types = environment.result_types.clone();
let has_result_types = !result_types.is_empty();

Ok(if let Ok(results) = results.cast_as::<PyTuple>(py) {
results
Expand All @@ -173,7 +176,7 @@ impl Function {
.map_err(|error| {
wasmer::RuntimeError::new(io::Error::from(error).to_string())
})?
} else if !results.is_none(py) && !result_types.is_empty() {
} else if !results.is_none(py) && has_result_types {
vec![to_wasm_value((
results
.cast_as::<PyAny>(py)
Expand Down

0 comments on commit e57f02d

Please sign in to comment.