Created
January 27, 2025 17:19
-
-
Save Andoryuuta/34e7a01412a5e96536a20d24d18794e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rquickjs::{Context, Function, Module, Runtime}; | |
// When this is called from JS, rquickjs will seamlessly handle the conversion from JS values/objects -> rust types. | |
// If the types aren't correct, it will throw an exception. | |
fn some_rust_fn(cb: Function, arg1: i32, arg2: i32) { | |
println!("Rust: some_rust_fn - called with ({arg1}, {arg2})"); | |
// Call the callback - rquickjs will seamlessly handle the call in the opposite direction as well. | |
let result: i32 = cb.call((arg1, arg2)).unwrap(); | |
println!("Rust: some_rust_fn - JS callback result: {result}"); | |
} | |
fn main() { | |
println!("Rust: start"); | |
let rt = Runtime::new().unwrap(); | |
let ctx = Context::full(&rt).unwrap(); | |
ctx.with(|ctx| { | |
let global = ctx.globals(); | |
// Register some rust functions into the global context | |
global | |
.set( | |
"someRustFn", | |
Function::new(ctx.clone(), some_rust_fn).unwrap(), | |
) | |
.unwrap(); | |
// Run the actual javascript code. | |
Module::evaluate( | |
ctx.clone(), | |
"test", | |
r#" | |
var sum = (a, b) => { | |
return a + b | |
}; | |
someRustFn(sum, 3, 7); | |
"#, | |
) | |
.unwrap() | |
.finish::<()>() | |
.unwrap(); | |
}); | |
println!("Rust: end"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rust: start | |
Rust: some_rust_fn - called with (3, 7) | |
Rust: some_rust_fn - JS callback result: 10 | |
Rust: end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment