我有两个名为IPCBase和DispatchData的类。现在我想把QDataStrean对象drom IPCBase传递给DispatchData。首先,我尝试使用Connect语句直接发送它。但是它会给出错误,比如QDataStream对象没有在QRegisterMatatype中注册。
编辑::我也参考了这个链接
When, where and why use namespace when registering custom types for Qt
所以我做了一些类似这样的事情
typedef QDataStream* myDataStrem;
Q_DECLARE_METATYPE(myDataStrem)然后在另一个类中使用connect语句(DispatchData)
connect(mpThrIPCReceiver, SIGNAL(dispatchReadData(const int&, myDataStrem)),
this, SLOT(onIPCDataReceived(const int&, myDataStrem)));onIPCDataReceived插槽
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.
}发布于 2016-06-17 03:16:12
这看起来像是在传递一个悬空指针:当接收线程到达数据流时,数据流似乎已经不存在了。即使您在源对象中延长了它的生命周期,通过信号槽连接传递原始指针也不是一个好主意。如果源类可能会消失,而接收方线程有一个挂起的槽调用,那么您仍将在接收方使用悬空指针。传递一个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"https://stackoverflow.com/questions/37850584
复制相似问题