Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass values to/from [callback] function? #7

Open
lukeed opened this issue Feb 13, 2023 · 1 comment
Open

Pass values to/from [callback] function? #7

lukeed opened this issue Feb 13, 2023 · 1 comment

Comments

@lukeed
Copy link

lukeed commented Feb 13, 2023

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!

@mishushakov
Copy link
Contributor

mishushakov commented Jul 3, 2023

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())
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants