Search code examples
c++qtqjsengine

How to clean up or destroy QJSEngine?


I'm putting together an application using Qt 5.12 where users will load JS scripts that interact with the app through its API. These scripts are bundled into "projects" (i.e multiple JS modules that depend on each other), and at any time I want only one project to be loaded into the JS engine, so if the user loads a different project, I want the previous context to be cleaned up.

Based on the documentation, I assumed that if I just delete the QJSEngine object and create a new one, this will allow me to create a fresh JS context.

QJSEngine* jsEngine = new QJSEngine();

// Load JS modules and run code...

jsEngine->collectGarbage();
delete jsEngine;

jsEngine = new QJSEngine();

// Load new JS modules...

When I try to run this code, I get an access violation exception at delete jsEngine. This is really strange, because the documentation itself states

Garbage is not collected from the persistent JS heap during QJSEngine destruction. If you need all memory freed, call collectGarbage manually right before destroying the QJSEngine.

which to me implied that I should be able to do this. Anyone have any ideas? Thanks in advance!


Solution

  • Okay, so it turns out I'm a dummy and forgot to include one important detail: my application also exposes my "JavaScript interface" object to the JS engine using QJSEngine::newQObject, so I was pretty much just recreating this issue.

    The solution is exactly the same: using QQmlEngine::setObjectOwnership makes the problem go away.