how-to guide
Manage values, local scopes, and errors in C
Avoid manual bk_free_value calls in loops, inspect thrown exceptions, and share one runtime across multiple realms.
Use a local scope for temporary values
Outside a local scope, value-returning calls allocate owned registry roots that must be freed with bk_free_value.
Open a local scope to release all temporary handles at once, and escape the single handle you want to keep:
bk_scope scope = bk_scope_open(js);
for (int i = 0; i < 1000; i++) {
bk_value n = bk_new_number(js, i);
bk_set_property_uint32(js, array, i, n);
}
bk_value result = bk_scope_close_escape(js, scope, array);
A scope holds up to 131,072 values. For larger loops, open a nested scope inside the loop body.
Immediate handles (BK_UNDEFINED, BK_NULL, BK_TRUE, BK_FALSE) never consume a slot.
Check and take exceptions
Value-returning functions return BK_EXCEPTION on failure. Check with bk_is_exception and take the thrown value with bk_get_exception:
bk_value v = bk_eval(js, "throw new TypeError('bad input')");
if (bk_is_exception(v)) {
bk_value err = bk_get_exception(js);
fprintf(stderr, "%s\n", bk_cstr(js, err, NULL));
bk_free_value(js, err);
}
Share one runtime across multiple realms
Create a bk_runtime explicitly when you need multiple independent global objects (realms) that share a heap and can pass values without cloning:
bk_runtime rt = bk_new_runtime(NULL);
bk_ctx app = bk_new_context(rt, NULL);
bk_ctx other = bk_new_context(rt, NULL);
/* evaluate in app and other */
bk_free_context(other);
bk_free_context(app);
bk_free_runtime(rt);
Realms share memory and are not a security boundary. For hard isolation or concurrent threads, create separate runtimes.