Exception when trying to use googletest to test ATL object - atl

I want to write some unit tests for my COM object using googletest. Unfortunately I get an exception when CreateInstance is called: 0xC0000005: Access violation reading location 0x00000000.
The code basically looks like this:
MyClass.h
class ATL_NO_VTABLE CMyClass
: public CComObjectRootEx<CComMultiThreadModel>,
public CComCoClass<CMyClass, &CLSID_MyClass>,
public IConnectionPointImpl<CMyClass, &IID_IMyClassListener>,
public IConnectionPointContainerImpl<CMyClass>,
public IDispatchImpl<MyComClass, &IID_MyComClass, &LIBID_MyLib, 1, 0>
{
...
}
Test.cpp
#include "stdafx.h"
#include "gtest/gtest.h"
#include "MyClass.h"
TEST(MyClassTest, IsCreated)
{
HRESULT hr(E_FAIL);
CComPtr<MyComClass> lMyObject;
hr = CMyClass::CreateInstance(&lMyObject);
EXPECT_EQ(S_OK, hr);
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
I am able to call CreateInstance without any problems in some existing (non-test) projects. I don't really understand COM/ATL so I'm having trouble figuring out why I'm getting this weird exception.

#Roman had the right idea. I put the following above main() in my Test.cpp and everything started working:
#include "resource.h"
const IID LIBID_TestLib = {0xA5AD0596, 0x14AE, 0x43A3, {0xB2, 0x5E, 0xF7, 0xF9, 0x19, 0x93, 0xA7, 0x24}};
class CTestModule : public CAtlExeModuleT<CTestModule>
{
public:
DECLARE_LIBID(LIBID_TestLib)
DECLARE_REGISTRY_APPID_RESOURCEID(IDR_TEST, "{575D971E-C35B-470f-BE6B-FFB9145CCCD3}")
};
CTestModule gAtlModule;

Related

C++ determine best way for external class pointer

For a c++ application which I'm currently being busy to develop, I have several classes which I need to access through my entire code, without creating a new object
So searching I have found that one of methods that can be used is with the extern linkage specifier.
I would like to know what is best way to use this extern method, I wrote a little sample code
classone.h
#ifndef CLASSONE_H
#define CLASSONE_H
class ClassOne
{
public:
ClassOne();
void showClassOneInt();
private:
int m_classOneInt;
};
extern ClassOne *classOne;
---------------------------------------
classone.cpp
#include "classone.h"
#include <QDebug>
ClassOne *classOne;
ClassOne::ClassOne()
{
m_classOneInt = 1;
}
void ClassOne::showClassOneInt()
{
qDebug() << "ClassOneInt: " << m_classOneInt;
}
---------------------------------------
classtwo.h
#ifndef CLASSTWO_H
#define CLASSTWO_H
class ClassTwo
{
public:
ClassTwo();
void showClassTwoInt();
private:
int m_classTwoInt;
};
#endif // CLASSTWO_H
---------------------------------------
classtwo.cpp
#include "classtwo.h"
#include <QDebug>
ClassTwo::ClassTwo()
{
m_classTwoInt = 2;
}
void ClassTwo::showClassTwoInt()
{
qDebug() << "ClassTwoInt: " << m_classTwoInt;
}
---------------------------------------
classthree.h
#ifndef CLASSTHREE_H
#define CLASSTHREE_H
class ClassThree
{
public:
ClassThree();
void showClassThreeInt();
private:
int m_classThreeInt;
};
#endif // CLASSTHREE_H
---------------------------------------
classthree.cpp
#include "classthree.h"
#include <QDebug>
ClassThree::ClassThree()
{
m_classThreeInt = 3;
}
void ClassThree::showClassThreeInt()
{
qDebug() << "ClassThreeInit: " << m_classThreeInt;
}
---------------------------------------
classtest.cpp
#include "classtest.h"
#include "classone.h"
#include "classtwo.h"
#include "classthree.h"
//Class one pointer already in header
//Class two
extern ClassTwo *classTwo;
//Class three
extern ClassThree *classThree;
ClassTest::ClassTest()
{
//Execute class one
classOne->showClassOneInt();
//Execute class two
classTwo->showClassTwoInt();
//Execute class three
classThree->showClassThreeInt();
}
---------------------------------------
main.cpp
#include <QCoreApplication>
#include "classone.h"
#include "classtwo.h"
#include "classthree.h"
#include "classtest.h"
//Class one pointer already in header file
//Class two pointer
ClassTwo *classTwo;
//Class three pointer
ClassThree *classThree;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//Create object for class one
classOne = new ClassOne;
//Create object for class two
classTwo = new ClassTwo;
//Create object for class three
ClassThree three;
classThree = &three;
//Create a classTest object
ClassTest test;
return a.exec();
}
Please could you tell me what is the best way, thanks for you help.
The best way is to not do it and instead use dependency injection.
If you choose to do it anyway, you should at least use getter/factory functions (i.e. ClassOne &getClassOne())) so you can:
be sure random code can't change the objects and
handle order of construction implicitly by constructing on first use (sometimes appropriate, sometimes not).
Having a global state is generally not a great idea, seek to eliminate it.
If that cannot be done, try the singleton pattern.
class Singleton
{
Singleton(); //keep constructors private to avoid creation by others
static Singleton inst;
public:
static Singleton& Instance() {return inst;}
};
Singleton Singleton::inst;

QTcpServer not working

I'm trying to create a TCP server in C++ with QT. I have the code but as soon as I try to connect to the server with SocketTest it says connection refused (most likely due to the server not running).
This is in my tcplistener.h:
#ifndef TCPLISTENER_H
#define TCPLISTENER_H
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QTcpServer>
class tcp_listener : public QTcpServer
{
Q_OBJECT
signals:
public slots:
void newConnectionFromServer()
{
QTcpSocket* newConnection = nextPendingConnection();
qDebug("New connection from %d", newConnection->peerAddress().toIPv4Address());
}
public:
tcp_listener(QObject *parent = 0)
: QTcpServer(parent)
{
listen(QHostAddress::Any, 30000);
connect(this, SIGNAL(newConnection()), SLOT(newConnectionFromServer()));
}
};
#endif // TCPLISTENER_H
This is in my engine.h:
#ifndef ENGINE_H
#define ENGINE_H
#include <QCoreApplication>
#include "tcplistener.h"
class engine
{
public:
void init()
{
qDebug("Initializing AuraEmu...");
tcp_listener list();
}
};
#endif // ENGINE_H
And this is my main.cpp:
#include <QCoreApplication>
#include "engine.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
engine eng = engine();
eng.init();
return a.exec();
}
Anybody know what the problem is?
The other answer, and my comment before that already cover what you did wrong, so I'll just supply the solution.
I've added comments because you said you come from Java and C#, but really, don't try to program C++ like it's Java or C#, because it's not.
class engine
{
public:
void init()
{
qDebug("Initializing AuraEmu...");
tcp_listener *list = new tcp_listener(); // Allocate on the heap instead of the stack.
}
~engine()
{
delete list; // C++ is an UNMANAGED language, there is no garbage collector
}
private:
tcp_listener *list; // This is a pointer to an object.
};
eng.init();
here you create
tcp_listener list();
and after eng.init() finished you detroy it, because
it is object on stack.

Issue with inheritance in Qt

Basically I am trying to inherit everything from friction into base (or even the other way round) however, it is not identifying the classes I put in.
base.h
#ifndef BASE_H
#define BASE_H
#include <QMainWindow>
namespace Ui {
class Base;
}
class Base : public QMainWindow{
Q_OBJECT
public:
explicit Base(QWidget *parent = 0);
~Base();
private:
Ui::Base *ui;
};
#endif // BASE_H
friction.h:
#ifndef FRICTION_H
#define FRICTION_H
class Friction : public Base{ // THIS IS WHERE THE ERROR IS
public:
Friction();
};
#endif // FRICTION_H
base.cpp
#include "friction.h"
#include "base.h"
#include "ui_base.h"
Base::Base(QWidget *parent) :QMainWindow(parent),ui(new Ui::Base){
ui->setupUi(this);
}
Base::~Base(){
delete ui;
}
friction.cpp
#include "friction.h"
#include "base.h"
#include "ui_base.h"
Friction::Friction(){
}
and finally main.cpp
int main(int argc, char *argv[]){
QApplication a(argc, argv);
Base w;
w.show();
Friction f;
return a.exec();
}
I receive the error "expected class name before '{' token", I have cut the project down as much as I can and the error still comes up and I really don't know why.
I am fairly new to c++ however I find inheritance not much of an issue on a basic program but upon moving to Qt I couldn't seem to get it working. I have tried numerous things regarding changing the includes etc etc as I am completely oblivious as to why it's not identifying the class.
If friction inherits Base , than you should put:
#include "base.h"
in friction.h file , like so:
#ifndef FRICTION_H
#define FRICTION_H
#include "base.h"
class Friction : public Base{ // THIS IS WHERE THE ERROR IS
public:
Friction();
};

C++/Qt Q_OBJECT macro causes an error

I've just started programming in Qt framework. Following is a very simple program:
#include <QtCore/QCoreApplication>
#include <QDebug>
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass() {}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyClass *c = new MyClass();
return a.exec();
}
But I receive following error when I try to compile & run it:
In function MyClass:
undefined reference to vtable for MyClass
But when I remove the QObject macro everything works fine. Please note that the class is defined in the same file as the main function.
I'm using Qt version 4.7, running on Win 7.
What is causing this issue?
Update: I get the same error when I define my class in a separate header file. mytimer.h:
#ifndef MYTIMER_H
#define MYTIMER_H
#include <QtCore>
class MyTimer : public QObject
{
Q_OBJECT
public:
QTimer *timer;
MyTimer();
public slots:
void DisplayMessage();
};
#endif // MYTIMER_H
mytimer.cpp:
#include "mytimer.h"
#include <QtCore>
MyTimer::MyTimer()
{
timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(DisplayMessage()));
timer->start(1000);
}
void MyTimer::DisplayMessage()
{
qDebug() << "timed out";
}
And this is the main.cpp:
#include <QtCore/QCoreApplication>
#include <QDebug>
#include "mytimer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyTimer *mt = new MyTimer();
return a.exec();
}
You need to compile it using qmake, which is going to create mock methods for your custom QObject class. See here about more on generating moc files.
Since your example doesn't contain header files, it is not parsed, and no moc files are generated. You need to declare MyClass in a separate header file, and run moc generation tool.
When you are using QT Creator you should cleanup up your project and execute qmake, in the build menu.
Whenever u apply some changes first clean your project, then run qmake, and the finally build your project...

Qt4 QNetworkManager Hangs

I'm trying to write an application using QNetworkManager. I have simplified the code down to the problem. The following code hangs, and I have no idea why:
main.cpp:
#include <QApplication>
#include "post.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
post("http://google.com/search", "q=test");
return app.exec();
}
post.h:
#ifndef _H_POST
#define _H_POST
#include <QNetworkAccessManager>
#include <QNetworkRequest>
class post : public QObject {
Q_OBJECT
public:
post(QString URL, QString data);
public slots:
void postFinished(QNetworkReply* reply);
protected:
QNetworkAccessManager *connection;
};
#endif
post.cpp:
#include <QApplication>
#include <QUrl>
#include "post.h"
post::post(QString URL, QString data) {
connection = new QNetworkAccessManager(this);
connect(connection, SIGNAL(finished(QNetworkReply*)), this, SLOT(postFinished(QNetworkReply*)));
connection->post(QNetworkRequest(QUrl(URL)), data.toAscii());
}
void post::postFinished(QNetworkReply*) {
qApp->exit(0);
}
Some Googling shows it may be because I have everything on one thread, but I have no idea how to change that in Qt... none of the network examples show this.
I just tried it with the same results. The problem is that you are creating the post object by only calling the constructor. Since you are not specifying an object it is getting destroyed right away (to check this create a destructor and see when it gets called.)
try:
post p("http://google.com/search","q=test");
Then your slot gets called.