Is it possible to emit a signal on behalf of another QObject? the reason I would like to do this is that it would be very useful when writing mock/test code and simply want to simulate that a certain object emitted a signal.
I tried to use
QMetaObject::invokeMethod(otherObject, "mySignal", Q_ARG(QString, myArg));
because the documentation says:
[...] Invokes the member (a signal or a slot name) on the object obj.[...]
But this does not work for me. The signal is simply not emitted.
You can simply invoke the signal through the class like so:
otherObject.mySignal("Testing!");
Edit
Good point on the thread-safety issue. I got it to work as well with the invokeMethod solution by explicitly setting the connection type. If your objects are in different threads, you'd need to use the QueuedConnection rather than the DirectConnection. Here is my simple test case:
main.cpp
#include <QObject>
#include "Stub.h"
int main()
{
Stub stub;
Stub2 stub2;
QObject::connect(&stub, &Stub::TestSignal, &stub2, &Stub2::TestReceiver);
QMetaObject::invokeMethod(&stub,
"TestSignal",
Qt::DirectConnection,
Q_ARG(QString, "myArg"));
return 0;
}
Stub.h
#ifndef STUB_H
#define STUB_H
#include <QObject>
#include <QDebug>
class Stub : public QObject
{
Q_OBJECT
signals:
void TestSignal(QString s);
};
class Stub2 : public QObject
{
Q_OBJECT
public:
void TestReceiver(QString s) {qDebug() << "Got s:" << s;}
};
#endif // STUB_H
Related
Im trying to write a wrapper in c++/cli for an DLL, which code i dont have, only DLL file and header but i created lib file through VS command prompt. When i`m trying to build solution i receive this errors:
DotNetWrappOfAsterSdkDll.obj : error LNK2028: unresolved token (0A00002E) "void __stdcall MuteClearLastError(void)" (?MuteClearLastError##$$FYGXXZ) referenced in function "public: void __clrcall DotNetWrappOfAsterSdkDll::WrapperClass2::doMuteClearLastError(void)" (?doMuteClearLastError#WrapperClass2#DotNetWrappOfAsterSdkDll##$$FQ$AAMXXZ)
DotNetWrappOfAsterSdkDll.obj : error LNK2019: unresolved external symbol "void __stdcall MuteClearLastError(void)" (?MuteClearLastError##$$FYGXXZ) referenced in function "public: void __clrcall DotNetWrappOfAsterSdkDll::WrapperClass2::doMuteClearLastError(void)" (?doMuteClearLastError#WrapperClass2#DotNetWrappOfAsterSdkDll##$$FQ$AAMXXZ)
I tried to create my own DLL and include it to the wrapper, and its working perfectly
here dll created by me which i can use in c++/cli wrapper:
//header file
#pragma once
#define DLLEXP __declspec( dllexport )
namespace Computations {
DLLEXP void someMethod(int number);
}
//cpp file
#include "Computations.h"
#include <iostream>
#include <time.h>
//#include "pnl/pnl_random.h"
using namespace std;
void Computations::someMethod(int number)
{
std::cout << "something "<<number*number << endl;
}
and here is part of header of DLL which i want to use:
#ifndef MUTEIFC_H
#define MUTEIFC_H
#include <Windows.h>
#ifdef MUTEIFC_LIBRARY
# define MUTEAPI extern "C"__declspec(dllexport)
#else
# define MUTEAPI __declspec(dllimport)
#endif
#define MUTECALL __stdcall
/** \ingroup init */
/** Initialization of the ASTER SDK library
* \returns TRUE - success, FALSE - failure (use \ref MuteLastErrorCode or/and \ref MuteLastErrorInfo to get
* failure cause)
* \note This function will require Administrative privileges on the first call on a given computer.
*/
MUTEAPI BOOL MUTECALL MuteIfcInitialize(VOID);
/** \ingroup init */
/** Finialization of the ASTER SDK library
*/
MUTEAPI VOID MUTECALL MuteIfcFinalize(VOID);
/** \ingroup errors*/
/** Clears the calling thread's last-error code and description.
* The last-error is maintained on a per-thread basis. Multiple threads do not overwrite each other's last-error.
*/
MUTEAPI VOID MUTECALL MuteClearLastError(VOID);
#endif // MUTEIFC_H
and my c++/cli code :
//header file
#pragma once
#include "Computations.h"
#include "muteifc.h"
using namespace System;
namespace DotNetWrappOfAsterSdkDll
{
public ref class WrapperClass2
{
public:
void doMuteClearLastError();
};
public ref class WrapperClass
{
private:
public:
void getPriceCallEuro(int number);
};
}
//cpp file
#include "DotNetWrappOfAsterSdkDll.h"
using namespace DotNetWrappOfAsterSdkDll;
using namespace Computations;
namespace DotNetWrappOfAsterSdkDll
{
//this dont work
void WrapperClass2::doMuteClearLastError() {
MuteClearLastError();
}
//this works great
void WrapperClass::getPriceCallEuro(int number) {
someMethod(number);
//MuteIfcFinalize();
}
}
Please tell me what i'm doing wrong
You probably didn't add the lib that contains the function reference to the linker options.
Either the lib contains he code it self or it has a reference to the DLL that must be loaded. The linker will bring your code and the DLL (or static lib) code together...
I'm implementing a FSM using Boost's MSM library.
In the FSM, I have transition tables which describe Events, Source states, Target states, Actions and Guards.
It's my first time using a higher-level design of a state machine. In the past, I've just used switch statments and executed code. However, this one is going to be big and I wanted to keep everything organized properly so it doesn't turn into a mess.
I have an object that represents the state machine (it's a boost::msm::back::state_machine<MyStateMachine> where MyStateMachine is my implemenmtation which inherits from boost::msm::front::state_machine_def ).
The trick is that my business logic will be done in the Actions. I don't think that's uncommon for a FSM. Boost's examples seems to suggest that these Actions should be implemented as methods in the state machine itself, but I'm thinking that this just might make the one class too massive. I feel it makes sense to separate the work from the state machine.
Which makes more sense to keep a readable, maintainable, and extendable design?
Do the business logic in methods in the FSM class (I'm worried that this mixes state management with work too closely).
Do the business logic in the parent which instantiates the FSM. The FSM will need a pointer to the parent, and the parent will need to implement an interface that the FSM understands (that, or the FSM implementation will need to #include the declaration of the parent).
Do the business logic in a new class which is instantiated and owned by the FSM.
Do the business logic in a new class which is instantiated and owned by the parent, but passed as a reference (or pointer) to the FSM.
Something else.
It depends on your situation but I have one approach I usually use.
Maybe it is a variation of the 2 or 5.
Let's say your_app has your business logic. And it needs to behave as state-machine. I think that it is one of the typical use-case of the state-machine.
In this case, the state-machine can be placed as the nested class of the your_app. your_app has the member variable sm_, state-machine instance.
The definition of the state-machine is sm_def. It has the reference of the your_app.
When someone that is outside of the your_app want to process an event, call your_app::process_event(). If you don't want to provide direct event process interface, you can wrap it as your_app::handle_some(). If you do so, your_app::process_event() should be private.
Here is example implementation:
#include <iostream>
#include <boost/msm/back/state_machine.hpp>
#include <boost/msm/front/state_machine_def.hpp>
#include <boost/msm/front/functor_row.hpp>
namespace msm = boost::msm;
namespace msmf = boost::msm::front;
namespace mpl = boost::mpl;
// application domain
class your_app {
public:
your_app() :sm_(boost::ref(*this)) {
sm_.start(); // start state machine
}
// public interface for event processing
// Event definitions
struct Event1 {
int param;
};
template <typename Event>
void process_event(Event const& ev) {
sm_.process_event(ev);
}
void handle_some(int param) {
process_event(Event1 {param});
}
private:
// internal business logic triggered from the state machine
void do_some_business(int param) {
std::cout << "do_some_business " << param << std::endl;
}
// state machine definiition
struct sm_def:msmf::state_machine_def<sm_def> {
sm_def(your_app& ya):ya_(ya) {}
// States
struct State1:msmf::state<> {
template <class Event,class Fsm>
void on_entry(Event const&, Fsm&) {
std::cout << "State1::on_entry()" << std::endl;
}
template <class Event,class Fsm>
void on_exit(Event const&, Fsm&) {
std::cout << "State1::on_exit()" << std::endl;
}
};
struct State2:msmf::state<> {
template <class Event,class Fsm>
void on_entry(Event const&, Fsm&) {
std::cout << "State2::on_entry()" << std::endl;
}
template <class Event,class Fsm>
void on_exit(Event const&, Fsm&) {
std::cout << "State2::on_exit()" << std::endl;
}
};
// Set initial state
typedef State1 initial_state;
// Actions
struct Action {
template <class Event, class Fsm, class SourceState, class TargetState>
void operator()(Event const& e, Fsm& f, SourceState&, TargetState&) const {
// get your_app via Fsm.
f.ya_.do_some_business(e.param);
}
};
// Transition table
struct transition_table:mpl::vector<
// Start Event Next Action Guard
msmf::Row < State1, Event1, State2, Action, msmf::none >,
msmf::Row < State2, Event1, State1, Action, msmf::none >
> {};
your_app& ya_;
};
friend class sm; // give the friend access to the sm
typedef msm::back::state_machine<sm_def> sm;
sm sm_;
};
int main() {
your_app ya;
ya.process_event(your_app::Event1{42});
ya.handle_some(44);
}
And running demo: https://wandbox.org/permlink/PQGSGr0bnJHgaMpD
I have been trying to do the following to no avail,
In 'used.h',
#ifndef USED_H_
#define USED_H_
#include<iostream>
#include<string>
class used
{
public:
int member=0;
used();
virtual ~used();
};
#endif
In the used.cc,
#include "used.h"
used::used()
{
}
used::~used()
{
}
In 'the_user.h',
#ifndef THE_USER_H_
#define THE_USER_H_
#include<queue>
#include<iostream>
class used; //Class forward declaring
class the_user
{
public:
std::deque<used*> my_queue;
the_user();
~the_user();
};
#endif
Now, I want to access and change 'member' in 'the_user.cc',
#include "used.h"
#include "the_used.h"
#include<iostream>
#include<queue>
using namespace std;
the_user::the_user()
{
deque <used*> my_queue;
my_queue.resize(6);
used* object = new used; <-------marked line
for(unsigned int i=0; i<my_queue.size(); i++)
{
my_queue.push_back(object);
}
cout << my_queue[5] << endl; //Should give 0
my_queue[0]->member=1000;
cout << my_queue[0]->member << endl; //1000
}
in main file(I have only read access),
#include "the_used.h"
#include <iostream>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main()
{
the_used *object = new the_used();
}
Actually, I am getting undefined reference to used::used() at the marked line. What seems to be the problem?
I have tried to use the same for a vector as well but to no avail.
I am not allowed to make changes to the 'int main(){}'.
Any help would be highly appreciated.
Your class declaration doesn't declare any constructor or destructor:
class used
{
public:
int member=0;
};
But in your cpp file you define them. Your compiler should complain already here:
#include "used.h"
used::used()
{
}
used::~used()
{
}
You must declare constructor and destructor in your class:
class used
{
public:
used();
~used();
int member=0;
};
Then here:
my_queue.resize(6);
you will actually create 6 pointers that will be initialized to nullptr. Maybe you're aware of that, since you expect my_queue[5] to return 0.
Then in your loop, everytime you do this:
my_queue.push_back(object);
you will increase the size of my_queue by one, thus make your loop run forever.
Apart from that: Do. Not. Do. using namespace std;. Ever.
I just started using Gtest/Gmocks and I'm struggling with an example. I have a simple class which has a member a function that returns a value(say 3). I'm trying to mock this test and check if the returned result is 3. For simplicity I wrote everything in a single file:
// Testing.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "gmock\gmock.h"
#include "gtest\gtest.h"
using ::testing::AtLeast;
using namespace std;
class MyClass{
public:
virtual int retValue() { return 3; }
virtual ~MyClass(){}
};
class FakeMyClass : public MyClass
{
public:
MOCK_METHOD0( retValue, int() );
};
TEST(TestForMyClass, TestRetVal)
{
FakeMyClass obj3;
EXPECT_EQ(obj3.retValue(), 3);
}
int _tmain(int argc, _TCHAR* argv[])
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
However my test fails and it says that expected result is 3 and my actual result is 0.
I've watched a couple of examples and I think I did everything as shown in there still the result is not what I'm expecting. Please help me see where I'm wrong and how can I make that test to pass. Thank you.
The simple answer to your question is:
You have an object of your mock FakeMyClass. This object will never return the value of the base class, if you override this method!!
If you want to test a simple method of a class, you do not need a mock. Just test your class:
class MyClass{
public:
virtual int retValue() { return 3; }
virtual ~MyClass(){}
};
TEST(TestForMyClass, TestRetVal)
{
MyClass obj3;
EXPECT_EQ(obj3.retValue(), 3);
}
Little bit more to mocking:
A principle of testing is to test in isolation. So, when your class is in a relation to another object, you have to mock this object. I suggest to take a look on an example
(e.g. klick).
In this example the Painter is the system under test. The Paintercommunicates with the Turtle, which is mocked.
I have some library code which has some legacy code I'd like to move away from. To do so, I've started marking the outdated methods as deprecated. Where those methods call each other, I get deprecation warnings which I'd rather not see (the new functionality means you just need a single call as less of the internals of the classes workings are exposed).
Is there a way to suppress the deprecation warning for the call from OldMethod to OldMethodHelper? ..or a better way to do this altogether?
For example (in MyClass.h):
public ref class MyClass
{
public:
[Obsolete]
void OldMethodHelper();
[Obsolete]
void OldMethod();
void NewMethod();
};
In MyClass.cpp:
void MyClass::OldMethodHelper()
{
// Some old helper method that's called both from within this class and externally.
}
void MyClass::OldMethod()
{
OldMethodHelper(); // I don't want this call to raise a deprecation warning.
}
void MyClass::NewMethod()
{
// A new method which replaces the calls to both of the previous methods.
}
Code is called like this:
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
MyClass m;
m.OldMethodHelper(); // This should raise a deprecation warning.
m.OldMethod(); // This should raise a deprecation warning.
m.NewMethod();
return 0;
}
Edit - I found another post on SO which suggests using #pragma warning(disable: 4996) is a possibility but it seems like a bit of a clunky way to approach the problem to me:
void MyClass::OldMethod()
{
#pragma warning(push)
#pragma warning(disable: 4996) //4996 for _CRT_SECURE_NO_WARNINGS equivalent
OldMethodHelper(); // I don't want this call to raise a deprecation warning.
#pragma warning(pop)
}
Edit2 - Made some corrections / clarifications to the code example.
Speaking without proof, but maybe a macro could help here. Easier to show than to explain:
MyClass.h
---------
#ifndef MYCLASS_DEPRECATE
#define MYCLASS_DEPRECATE [Obsolete]
#endif
class MyClass
{
MYCLASS_DEPRECATE void OldMethodHelper();
...
}
MyClass.cpp
-----------
#define MYCLASS_DEPRECATE
#include "MyClass.h"
// The rest of the code