PDA

View Full Version : QtScript and c++ object lifetime: create in script, using in c++ code



sergey_85
26th February 2010, 08:39
Hi!
In my application I need to create object in script (var x = new MyWrapObject()) and then use it at c++ code

Have I any problems with memory leak or maybe script garbage collector delete object then I use it in c++ code

Qt help:


Controlling QObject Ownership

By default, the script engine does not take ownership of the QObject that is passed to QScriptEngine::newQObject(); the object is managed according to Qt's object ownership (see Object Trees and Object Ownership). You can change this behavior by specifying a different ownership mode as the second argument, overriding the default (QScriptEngine::QtOwnership).

Specifying QScriptEngine::ScriptOwnership as the ownership mode will cause the script engine to take full ownership of the QObject and delete it when it determines that it is safe to do so. This ownership mode is appropriate if the QObject does not have a parent object, and/or the QObject is created in the context of the script engine and is not intended to outlive the script engine.

For example, a constructor function that constructs QObjects only to be used in the script environment is a good candidate:
QScriptValue myQObjectConstructor(QScriptContext *context, QScriptEngine *engine)
{
// let the engine manage the new object's lifetime.
return engine->newQObject(new MyQObject(), QScriptEngine::ScriptOwnership);
}

Another ownership mode is QScriptEngine::AutoOwnership, where the ownership is based on whether the QObject has a parent or not. If the QtScript garbage collector finds that the QObject is no longer referenced within the script environment, the QObject will be deleted only if it does not have a parent.

JohannesMunk
27th February 2010, 10:33
Just call a special c++ function from script, that creates the object. Thats what the constructor function is anyway, when you have declared your own.

There, when you return the qobjects script value back using engine->newQObject(), just pass QtOwnership as parameter. Then script garbage collection will not delete your object.

If you need to use it in c++ code, you will have to find some way of accessing it. Just store a pointer/pointers to your object(s) when you create them.

HIH

Johannes