c++ - 在 catch-all 回调中识别来自 QDBusPendingCallWatcher 的原始调用

标签 c++ qt dbus

我想使用 Qt 的 QDBusPendingCallWatcher 来跟踪某些 D-Bus 调用的响应。我可以进行几种不同的 D-Bus 调用,但我想对所有这些调用进行一次回调。

问题是 QDBusPendingCallWatcher 在返回值就绪时发出的 finished 信号只有一个指向 QDBusPendingCallWatcher 本身的指针,而我找不到获取原始 QDBusMessage 的方法(其中包含被调用的方法)。

深入研究 Qt 的源代码,您可以看到调用 asyncCall 会创建 QDBusMessage,然后将其传递给正在使用的 QDBusConnection ,但遗憾的是,信息是使用 QDBusPendingCallPrivate 中的 pimpl 模式存储的,并且似乎无法从客户端代码中恢复。

TL;DR:是否有可能从 QDBusPendingCallWatcher::finished 信号触发的槽中知道异步 D-Bus 调用的方法名称?

最佳答案

如您所知,似乎无法取回原始消息。但是,我至少可以看到两个解决方法。由于 QDbusPendingCallWatcher 继承自 QObject,您可以在观察器上设置一个属性来保留方法调用的名称。或者,您可以使用 lambda 函数向回调添加更多信息(例如方法名称)。

DBusCaller::DBusCaller(QObject *parent) : QObject(parent)
{
    QDBusInterface connSettings("org.freedesktop.NetworkManager",                                    "/org/freedesktop/NetworkManager/Settings/1",                              
"org.freedesktop.NetworkManager.Settings.Connection",
                            QDBusConnection::systemBus() );

    //Method 1: set a property on the object
    {
        QDBusPendingCall pending = connSettings.asyncCall( "GetSettings" );
        QDBusPendingCallWatcher* watch = new QDBusPendingCallWatcher( pending );
        watch->setProperty( "method", "GetSettings" );
        connect( watch, &QDBusPendingCallWatcher::finished,
             this, &DBusCaller::callFinished );
    }

    //Method 2: use a lambda to add more information to our callback
    {
        QString methodName = "GetSettings";
        QDBusPendingCall pending = connSettings.asyncCall( methodName );
        QDBusPendingCallWatcher* watch = new QDBusPendingCallWatcher( pending );
        connect( watch, &QDBusPendingCallWatcher::finished,
             this, [=](QDBusPendingCallWatcher* reply) { callFinishedString( methodName, reply ); });
    }
}

void DBusCaller::callFinished(QDBusPendingCallWatcher* pending){
    pending->deleteLater();
    qDebug() << "Pending finished.  Method: " << pending->property( "method" );
}

void DBusCaller::callFinishedString(QString methodName, 
QDBusPendingCallWatcher *watch){
    watch->deleteLater();
    qDebug() << "Pending finsihed.  Method: " << methodName;
}

关于c++ - 在 catch-all 回调中识别来自 QDBusPendingCallWatcher 的原始调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48151342/

相关文章:

python - 声明在 DBus 上订阅了哪些信号?

c++ - Windows Qt 二进制安装程序是否支持开箱即用的 DBus?

c++ - 函数模板 : why ambiguity is generated?

c++ - static_cast 安全

c++ - c++ - 如何限制char数组仅从c++中的字符串中获取a和b?

c++ - 了解 Windows 中的 AlphaBlending

windows - 如何为我的应用程序设置 Windows 10 通知首选项

python - 在 PyQT4 程序中无法获得多语言支持

c++ - 如果在没有 QDebug 消息的情况下运行,Qt 应用程序会崩溃

linux - D-Bus线程模型