pub unsafe fn to_bytecode(
    context: *mut JSContext,
    compiled_func: &JSValueRef
) -> Vec<u8>
Expand description

write a function to bytecode

Example

use quickjs_runtime::builder::QuickJsRuntimeBuilder;
use hirofa_utils::js_utils::Script;
use quickjs_runtime::quickjs_utils::primitives;
use quickjs_runtime::quickjs_utils::compile::{compile, run_compiled_function, to_bytecode, from_bytecode};
let rt = QuickJsRuntimeBuilder::new().build();
rt.exe_rt_task_in_event_loop(|q_js_rt| {
    unsafe {
    let q_ctx = q_js_rt.get_main_context();
    let func_res = compile(q_ctx.context, Script::new("test_func.es", "let a = 7; let b = 5; a * b;"));
    let func = func_res.ok().expect("func compile failed");
    let bytecode: Vec<u8> = to_bytecode(q_ctx.context, &func);
    drop(func);
    assert!(!bytecode.is_empty());
        let func2_res = from_bytecode(q_ctx.context, &bytecode);
        let func2 = func2_res.ok().expect("could not read bytecode");
        let run_res = run_compiled_function(q_ctx.context, &func2);
        let res = run_res.ok().expect("run_compiled_function failed");
        let i_res = primitives::to_i32(&res);
        let i = i_res.ok().expect("could not convert to i32");
        assert_eq!(i, 7*5);
    }
});

Safety

When passing a context pointer please make sure the corresponding QuickJsContext is still valid