我有两个名为ipcbase和dispatchdata的类。现在,我想将qdatastrean对象drom ipcbase传递到dispatchdata。首先,我尝试使用Connect语句直接发送它。但是它给出了错误,例如qdatastream对象未在qregisterMatatype中注册。
edit ::我也引用了此链接
在注册QT的自定义类型时,何时,何地和为什么使用名称空间
所以我做了
之类的事情typedef QDataStream* myDataStrem;
Q_DECLARE_METATYPE(myDataStrem)
然后在另一类(dispatchdata)中连接语句
connect(mpThrIPCReceiver, SIGNAL(dispatchReadData(const int&, myDataStrem)),
this, SLOT(onIPCDataReceived(const int&, myDataStrem)));
onipcdataTaReceived插槽
void DispatchData::onIPCDataReceived(const int& msgType, myDataStrem dataReceived)
{
// dataReceived >> str1; Here it is giving error
// qDebug()<<"is"<<str1;
MemberFuncPointer f = mIPCCommandMapper.value(msgType);
(this->*f)(*dataReceived);
//This is function pointer which will rout it to respective function depending on the Message type.
然后它将来到这里
void DispatchData::onStartCountingCycle(QDataStream &dataReceived)
{
int data = 0;
dataReceived >> data; //Here it is crashing
//Giving error like
//pure virtual method called
//terminate called without an active exception
// I have debugged it and here dataReceived is becoming Readonly.
}
看来,您似乎是在悬空指针上传递:数据流似乎已经不再存在。即使您在源对象中延长了其寿命,也是通过信号插槽连接传递原始指针的一个坏主意。如果源类可能在接收器线程带有待处理的插槽调用时消失,则您仍然在接收器上使用悬空指针。最好通过QSharedPointer
或std::shared_ptr
。
以下工作,您当然可以使用共享指针中的任何类型。
#include <QtCore>
#include <cstdio>
struct Class : public QObject {
Q_SIGNAL void source(QSharedPointer<QTextStream>);
Q_SLOT void destination(QSharedPointer<QTextStream> stream) {
*stream << "Hello" << endl;
}
Q_OBJECT
};
Q_DECLARE_METATYPE(QSharedPointer<QTextStream>)
int main(int argc, char ** argv) {
QCoreApplication app{argc, argv};
Class c;
c.connect(&c, &Class::source, &c, &Class::destination, Qt::QueuedConnection);
auto out = QSharedPointer<QTextStream>(new QTextStream(stdout));
emit c.source(out);
QMetaObject::invokeMethod(&app, "quit", Qt::QueuedConnection);
*out << "About to exec" << endl;
return app.exec();
}
#include "main.moc"
输出:
About to exec
Hello
在现代QT上(至少5.6),在这种情况下,您无需致电qRegisterMetatype
。
使用std::shared_ptr
相同:
// https://github.com/KubaO/stackoverflown/tree/master/questions/datastream-pass-37850584
#include <QtCore>
#include <cstdio>
#include <memory>
struct Class : public QObject {
Q_SIGNAL void source(std::shared_ptr<QTextStream>);
Q_SLOT void destination(std::shared_ptr<QTextStream> stream) {
*stream << "Hello" << endl;
}
Q_OBJECT
};
Q_DECLARE_METATYPE(std::shared_ptr<QTextStream>)
int main(int argc, char ** argv) {
QCoreApplication app{argc, argv};
Class c;
c.connect(&c, &Class::source, &c, &Class::destination, Qt::QueuedConnection);
auto out = std::make_shared<QTextStream>(stdout);
emit c.source(out);
QMetaObject::invokeMethod(&app, "quit", Qt::QueuedConnection);
*out << "About to exec" << endl;
return app.exec();
}
#include "main.moc"