本文共 2127 字,大约阅读时间需要 7 分钟。
通过Dbus 总线,客户端调用服务端的槽函数
服务端在.pro工程中增加QT += dbus
定义接口名com.example.dbus.Interface
Q_CLASSINFO(“D-Bus Interface”,”com.example.dbus.Interface”)cal.h#include "qobject.h"class Cal : public QObject{ Q_OBJECT Q_CLASSINFO("D-Bus Interface","com.example.dbus.Interface")public: Cal();public slots: int add(int,int); int sub(int,int);};cal.cpp#include "cal.h"Cal::Cal() :QObject(){}int Cal::add(int a, int b){ return a+b;}int Cal::sub(int a, int b){ return a-b;}
qdbuscpp2xml -M cal.h -o com.example.dbus.xml
qdbusxml2cpp com.example.dbus.xml -a cal_adaptor qdbusxml2cpp com.example.dbus.xml -p cal_interface 将生成的文件加到工程中Cal *cal = new Cal(); new InterfaceAdaptor(cal); QDBusConnection connection = QDBusConnection::sessionBus();//注册服务名 connection.registerService("com.example.dbus"); //注册对象名 connection.registerObject("/", cal);
运行QT程序,用q-dfeet检查服务是否注册成功
测试: ~$ dbus-send –session –print-reply –dest=com.example.dbus / com.example.dbus.Interface.add int32:5 int32:6 method return sender=:1.1707 -> dest=:1.1710 reply_serial=2 int32 11客户端调用服务端的函数
新建工程QdbusTestClient
在.pro中增加QT += dbus 增加要访问的接口文件cal_interface.h cal_interface.cppQDBusConnection connection = QDBusConnection::sessionBus(); com::example::dbus::Interface *iface;//用interface新建一个iface接口//参数:com.example.dbus 是服务端创建的服务名,参数:/ 为服务端创建的Object Path//参数:connection 为申请的connection//参数:w.parent() 为当前对象this iface = new com::example::dbus::Interface("com.example.dbus","/", connection,w.parent()); QDBusPendingReply posReply = iface->add(15,10);//调用服务端的接口函数 posReply.waitForFinished(); qDebug() << posReply.value(); //输出返回结果25
测试
$ dbus-monitor --session \ "type='method_call',interface='com.example.dbus.Interface'"method call sender=:1.1837 -> dest=com.example.dbus serial=9 path=/; interface=com.example.dbus.Interface; member=add int32 15 int32 10
总结:服务端引入文件cal_adapter.h cal_adapter.cpp
客户端引入文件cal_interface.h cal_interface.cpp