Thursday 30 June 2011

QDBusArguments

Detailed Description

The QDBusArgument class is used to marshall and demarshall D-Bus arguments.
The class is used to send arguments over D-Bus to remote applications and to receive them back. D-Bus offers an extensible type system, based on a few primitive types and associations of them. See the QtDBus type system page for more information on the type system.
QDBusArgument is the central class in the QtDBus type system, providing functions to marshall and demarshall the primitive types. The compound types are then created by association of one or more of the primitive types in arrays, dictionaries or structures.
The following example illustrates how a structure containing an integer and a string can be constructed using the QtDBus type system:
struct MyStructure
 {
     int count;
     QString name;
 };
 Q_DECLARE_METATYPE(MyStructure)
In our case MyStructure is AlkUser

 // Marshall the MyStructure data into a D-Bus argument
 QDBusArgument &operator<<(QDBusArgument &argument, const MyStructure &mystruct)
 {
     argument.beginStructure();
     argument << mystruct.count << mystruct.name;
     argument.endStructure();
     return argument;
 }

 // Retrieve the MyStructure data from the D-Bus argument
 const QDBusArgument &operator>>(const QDBusArgument &argument, MyStructure &mystruct)
 {
     argument.beginStructure();
     argument >> mystruct.count >> mystruct.name;
     argument.endStructure();
     return argument;
 }
The type has to be registered with qDBusRegisterMetaType() before it can be used with QDBusArgument.
Therefore, somewhere in your program, you should add the following code:
qDBusRegisterMetaType<MyStructure>();
which we had already done in the backend.cpp 
with the code
qDBusRegisterMetaType<AlkUser>();
 
Once registered, a type can be used in outgoing method calls (placed with QDBusAbstractInterface::call()), signal emissions from registered objects or in incoming calls from remote applications.
It is important to note that the operator<< and operator>> streaming functions must always produce the same number of entries in case of structures, both in reading and in writing (marshalling and demarshalling), otherwise calls and signals may start to silently fail.
The following example illustrates this wrong usage in context of a class that may contain invalid data:
// Wrongly marshall the MyTime data into a D-Bus argument QDBusArgument &operator<<(QDBusArgument &argument, const MyTime &mytime) { argument.beginStructure(); if (mytime.isValid) argument << true << mytime.hour << mytime.minute << mytime.second; else argument << false; argument.endStructure(); return argument; } In this example, both the operator<< and the operator>> functions may produce a different number of reads/writes. This can confuse the QtDBus type system and should be avoided.

Reference: http://doc.qt.nokia.com/latest/qdbusargument.html#details
   

No comments:

Post a Comment