rusty_jsc
rusty_jsc copied to clipboard
Pass values to/from [callback] function?
trafficstars
I haven't been able to figure out how to pass value(s) to a Rust callback nor how to read an output value on the JS side from a Rust callback.
If you could provide a simple example for each of those that'd be very much appreciated!
The main example seems outdated, here's a working one:
use rusty_jsc::{JSContext, JSObject, JSValue};
use rusty_jsc_macros::callback;
#[callback]
fn foo(
ctx: JSContext,
function: JSObject,
this: JSObject,
args: &[JSValue],
) -> Result<JSValue, JSValue> {
println!("Argument value: {}", args[0].to_string(&ctx).unwrap());
Ok(JSValue::string(&ctx, "Returning a string from Rust!"))
}
fn main() {
let mut context = JSContext::default();
let callback = JSValue::callback(&context, Some(foo));
let global = context.get_global_object();
global.set_property(&context, "foo", callback).unwrap();
match context.evaluate_script("foo('Hello from Rust')", 1) {
Ok(value) => {
println!("{}", value.to_string(&context).unwrap());
}
Err(e) => {
println!("Uncaught: {}", e.to_string(&context).unwrap())
}
}
}