furiouzzF
Denoβ€’2y agoβ€’
6 replies
furiouzz

How to send an enum value from Rust to Deno

Hello there πŸ‘‹
I am quite a beginner to FFI and I am not sure which resources to read to learn more about it in Rust.
My problem: I got two enums MyEvent and MySubEvent.
#[repr(C)]
pub enum MySubEvent {
    X,
    Y(f64),
}

#[repr(C)]
pub enum MyEvent {
    Event(f64, f64),
    SubEvent(MySubEvent),
    Nothing,
}

I want to emit these events to callback function declared in Deno side
#[no_mangle]
pub extern "C" fn run_event_loop(func: Option<extern "C" fn(MyEvent)>) {
    let callback = func.unwrap();
    callback(MyEvent::Event(0., 36.));
    callback(MyEvent::SubEvent(MySubEvent::X));
    callback(MyEvent::SubEvent(MySubEvent::Y(1.0)));
    callback(MyEvent::Nothing);
}

I do not know how to recognize which event has been sent in Deno
const onEvent = new Deno.UnsafeCallback(
  {
    parameters: ["pointer"],
    result: "void",
  },
  (e) => {
    if (e === null) return;
    const view = new Deno.UnsafePointerView(e);
    const eventType = view.getUint32(); // Is it the right way to do it?
    console.log(eventType);
  }
);

const lib = Deno.dlopen("./target/debug/mylib.dylib", {
  run_event_loop: { parameters: ["function"], result: "void" },
});

lib.symbols.run_event_loop(onEvent.pointer);
lib.close();
Was this page helpful?