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

Sharing values between contexts in the same runtime #218

Open
mshick opened this issue Jan 15, 2025 · 1 comment
Open

Sharing values between contexts in the same runtime #218

mshick opened this issue Jan 15, 2025 · 1 comment

Comments

@mshick
Copy link

mshick commented Jan 15, 2025

I see this functionality mentioned in the readme, and in a couple of issues, notably #152 , but I can't seem to make it work.

My situation, simplified, is as below. I happen to be using the async variant, in case that has something to do with my inability to share across contexts.

async main() {
  const runtime = module.newRuntime();
  const context1 = runtime.newContext();

  await context1.evalCodeAsync(`
  function add(x) {
    return x + 50;
  };
  `);

    const test1Res = context.unwrapResult(await context1.evalCodeAsync(`add(50)`));
    console.log('add result1 (should be 100):', context1.getNumber(test1Res));
    test1Res.dispose();

    const contextPointer = context1.ctx.value;

   const context2 = runtime.newContext({contextPointer});
  
    // Throws with 'add' is not defined.
    const test2Res = context2.unwrapResult(await context2.evalCodeAsync(`add(10)`));
    console.log('add result2 (should be 60):', context2.getNumber(test2Res));
    test2Res.dispose();
}

Any help would be greatly appreciated.

@justjake
Copy link
Owner

Here context2 should actually a reference to context1 since they have the same underlying memory pointer address. The issue is there’s a bug in the asyncified runtime’s newContext method where it ignores the passed pointer, so you are actually getting two contexts in the same runtime.

I think you are misusing the API. There’s no point to having context JS objects pointing to the same context C pointer. To make a painful analogy, let’s say the pointer is a door, and the QuickJSContext object is a doorknob. What your code is trying to do is attach two doorknobs to the same door.

Contexts in a runtime do not share any globals. What I mean by “sharing values” is that you can take a handle returned from one context, and pass it as a parameter into another context, if the contexts share the same runtime.

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