Make C++ plugin function with complex arguments scriptable

Discussion forum for C++ and script developers who are using the QCAD development platform or who are looking to contribute to QCAD (translations, documentation, etc).

Moderator: andrew

Forum rules

Always indicate your operating system and QCAD version.

Attach drawing files, scripts and screenshots.

Post one question per topic.

Post Reply
User avatar
andrew
Site Admin
Posts: 9052
Joined: Fri Mar 30, 2007 6:07 am

Make C++ plugin function with complex arguments scriptable

Post by andrew » Thu Oct 30, 2014 1:59 pm

From a QCAD developer:
How can I make a class member function of a C++ plugin scriptable, with complex parameters or return values (such as a lists of vectors or a list of doubles)?

User avatar
andrew
Site Admin
Posts: 9052
Joined: Fri Mar 30, 2007 6:07 am

Re: Make C++ plugin function with complex arguments scriptab

Post by andrew » Thu Oct 30, 2014 2:11 pm

Let's have a look at such function from RVector:
static QList<double> RVector::getXList(const QList<RVector>& vectors);
This function expects a list of vectors as argument and returns a list of doubles.
In ECMAScript, the function might be called like this:
var res = RVector.getXList([new RVector(1,2), new RVector(3,4), new RVector(5,6)]);
// res==[1,3,5]
The script wrapper looks like this:
QScriptValue REcmaVector::getXList(QScriptContext* context, QScriptEngine* engine) {
    // check if one argument of type array is given:
    if (context->argumentCount()==1 && context->argument(0).isArray()) {
        // convert ECMAScript array to QList<RVector>:
        QList<RVector> a0;
        REcmaHelper::fromScriptValue(engine, context->argument(0), a0);

        // call C++ function:
        QList<double> cppResult = RVector::getXList(a0);
        return REcmaHelper::listToScriptValue(engine, cppResult);
    }
    else {
        return REcmaHelper::throwError("Wrong number/types of arguments for RVector.getXList().", context);
    }
}
REcmaHelper has many convenience functions to make script wrappers easier to implement. If your custom argument or return type is not supported by REcmaHelper, you might want to model your own helper function, similar like those provided in REcmaHelper.

Post Reply

Return to “QCAD Programming, Script Programming and Contributing”