C++/CLI multiple errors - visual-c++

I am getting multiple, confusing errors when building this school assignment and am hoping for some direction on what might be the problem. I wouldn't normally write it like this, but I put everything into one file as I try to debug this. Using Visual Studios Express 2012. I'm getting over 30 errors when I build, so I'm sure there is something fundamental that I am simply overlooking. Just a suggestion please, not looking for anyone to do my homework. Thanks
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include "MessageDisplayClass.h"
#include "LogMessageClass.h"
#include "TimerEventArgs.h"
using namespace System;
ref class CustomTimerClass
{
private:
static bool stopFlag = false;
// create instance of TimerEventArgs
TimerEventArgs^ timerEvent;
public:
CustomTimerClass(void)
{
}
delegate void CustomTimerClass::TimerAlarmHandler(/*Object^ sender, TimerEventArgs^ args*/);
event CustomTimerClass::TimerAlarmHandler^ OnTimerAlarm;
property bool StopFlag
{
bool get(void)
{
return stopFlag;
}
void set(bool b)
{
stopFlag = b;
}
}
void run()
{
Sleep(1000);
raiseTimerAlarm();
}
void OnStart()
{
// create instances of DisplayMessageClass and LogMessageClass classes
DisplayMessageClass^ messageDisplayer = gcnew DisplayMessageClass(this);
LogMessageClass^ messageLogger = gcnew LogMessageClass(this);
// display and log messages concerning this event
messageDisplayer->displayMessage(this, timerEvent);
messageLogger->logMessage(this, timerEvent);
}
void raiseTimerAlarm()
{
// create instance of TimerEventArgs and get time of instance creation
timerEvent = gcnew TimerEventArgs();
String^ eventTime = timerEvent->EventTime;
// tie this instance of CustomTimerClass to OnTimerAlarm event and start event
this->OnTimerAlarm += gcnew TimerAlarmHandler(this, &CustomTimerClass::OnStart);
OnTimerAlarm();
}
};
ref class MainProgram
{
int main(array<System::String ^> ^args)
{
CustomTimerClass^ timerClass = gcnew CustomTimerClass();
DisplayMessageClass^ messageClass = gcnew DisplayMessageClass();
LogMessageClass^ logerClass = gcnew LogMessageClass();
timerClass->run();
return 0;
}
};

At the point you're trying to use the various classes, the compiler doesn't know about them yet. Move your main() function to the end of the file. Or better, split your class definitions in their own header files and then include them in your main source file.
There are other related problems too. For example, you're trying to use the TimerEventArgs class before the compiler knows about it. So you need to move the class definition up. This is why it's best to have each class in its own header file, and then include it where needed. Though it's not strictly unnecessary, if you declare/define everything in the correct order.

Other than wrong order of declarations, it looks like the problem is that the compiler doesn't recognize the ^ bit, which suggests you're not compiling as C++/CLI. Righ-click the project in Solution Explorer and go to Configuration Properties -> General, and make sure that Common Language Runtime Support is set to Common Language Runtime Support (/clr).

For the benefit of anyone else (other newbies): As it turns out, my suspicion that the problem lay in the fact that some of the classes were "#including" each other was the problem. Using forward declarations, combined with having to create a separate class altogether to act as a variable storage handler was the solution to my problem.
Here are the two classes that were giving me the biggest problem, corrected to function correctly:
/*
CustomTimerClass.h
*/
#include "StdAfx.h"
#include "LogMessageClass.h"
#include "MessageDisplayClass.h"
#include "TimerEventArgs.h"
#include "Variables.h"
//ref class MessageDisplayClass;
//ref class Variables;
using namespace System;
ref class CustomTimerClass
{
private:
static bool stopFlag = false;
// create instance of TimerEventArgs
TimerEventArgs^ timerEvent;
// create instance of MessageDisplayClass and LogMessageClass
MessageDisplayClass^ messageDisplayer;
LogMessageClass^ messageLogger;
Variables^ flagVariable;
public:
CustomTimerClass(void)
{
}
delegate void CustomTimerClass::TimerAlarmHandler();
event CustomTimerClass::TimerAlarmHandler^ OnTimerAlarm;
property bool StopFlag
{
bool get(void)
{
return stopFlag;
}
void set(bool b)
{
stopFlag = flagVariable->Flag;
}
}
void run()
{
Sleep(1000);
raiseTimerAlarm();
}
void OnStart()
{
// create instances of DisplayMessageClass and LogMessageClass classes
messageDisplayer = gcnew MessageDisplayClass(this, flagVariable);
messageLogger = gcnew LogMessageClass(this);
// display and log messages concerning this event
messageDisplayer->displayMessage(this, timerEvent);
messageLogger->logMessage(this, timerEvent);
}
void raiseTimerAlarm()
{
// create instance of TimerEventArgs and get time of instance creation
timerEvent = gcnew TimerEventArgs();
String^ eventTime = timerEvent->EventTime;
// tie this instance of CustomTimerClass to OnTimerAlarm event and start event
this->OnTimerAlarm += gcnew TimerAlarmHandler(this, &CustomTimerClass::OnStart);
OnTimerAlarm();
}
};
/*
MessageDisplayClass serves to display a message that
represents the time at which the TimerEventArgs class is
instantiated. This time is returned through a function
of TimerEventArgs class.
*/
#pragma once
#include "stdafx.h"
#include <iostream>
#include "TimerEventArgs.h"
#include "Variables.h"
using namespace System;
ref class CustomTimerClass; // FORWARD DECLARATION HERE CAN
// ONLY BE USED FOR REFERENCE. CANNOT
// BE USED WHEN METHODS OF THE CLASS
// ARE CALLED
ref class MessageDisplayClass
{
private:
CustomTimerClass^ customTimerRef;
// Variables CLASS CREATED SOLELY TO ACT AS GO-BETWEEN BETWEEN
// MessageDisplayClass and CustomTimerClass
Variables^ variableRef;
static int counter;
public:
// constructor
MessageDisplayClass(CustomTimerClass^ CustomTimerClassInput, Variables^ variableReference)
{
customTimerRef = CustomTimerClassInput;
variableRef = gcnew Variables (CustomTimerClassInput);
}
void displayMessage(Object^ sender, TimerEventArgs^ timer)
{
counter ++;
if (counter > 0)
{
variableRef->Flag = true;
Console::WriteLine("Message: an event occured at time stamp: " + timer->EventTime);
}
}
};

Related

how to pass structure to QT thread

Am trying to pass data structure to QT thread and but no success.
here is what am doing and have done.
i prepare data for the thread, like this and then tried to pass prepared data to thread before starting.
void mytable::prepare_data(){
// get table row count
int rowCount = ui->my_table_view->rowCount();
// create structure array based on rowCount
pnp_com_info pnp_data[rowCount];
/* pnp_com_info structure defined it top of file below includes to make it global
struct pnp_com_info{
QString com_name = "";
int x = 0;
int y = 0;
int angle = 0;
bool status = false;
};
*/
// loop on table rows columns and load pnp_data with data of columns
// PROBLEM : how to pass pnp_data structure to thread side ?
// can pass basic vars like
RunJobThread->mynum = 10;
// start QT thread
RunJobThread->start();
// std:: thread experiment
// std::stdthreadtest(pnp_data,rowCount);
}
run_job_thread.h source code
#ifndef RUN_JOB_THREAD_H
#define RUN_JOB_THREAD_H
#include <QObject>
#include <QThread>
class run_job_thread : public QThread
{
Q_OBJECT
public:
run_job_thread();
void run();
int mynum;
struct pnp_com_info_thread{
QString com_name = "";
int x = 0;
int y = 0;
int angle = 0;
bool status = false;
};
bool Stop; // bool to stop the job
signals:
void select_row_of_table_signal(int);
public slots:
};
#endif // RUN_JOB_THREAD_H
run_job_thread.cpp source code
#include "run_job_thread.h"
#include <QtCore>
run_job_thread::run_job_thread()
{
}
// run the thread
void run_job_thread::run(){
qDebug() << "my num passed value is : "<<this->mynum; // output : 10
// Goal : loop on pnp_data structure and emit signal to table rows
emit select_row_of_table_signal(5);
}
things i tried
instead of struct i tried to use other data containers like map, multimap, vectors but they give error , as am initializing pnp_com_info struct inside mytable::prepare_data() function based on rowCount which make it local and limited to prepare_data() function but with map,multimap,vector my plan was that they will be global and i will be able to access it from thread, however it not worked.
std::map<std::string, int,int,int> pnp_com_info; // error: too many template arguments for class template 'map'
std::multimap<std::string, int,int,int,bool> pnp_com_info; // error: too many template arguments for class template 'multimap'
std::vector<std::string, int,int,int,bool> pnp_com_info; // error: too many template arguments for class template 'vector'
i also tried std::thread which was partial success , i mean it was working ok but looks like std::thread not works with QT GUI thread as upon running app GUI will go freez although std::thread was doing its job
I would suggest to do the following, because the declaration of the
pnp_com_info pnp_data[rowCount];
is inside a context i think their lifecycle will be lost once you leave it, other problem is that it would be really "unsafe" to create this kind of arrays and then pass it from one side to another. Therefore I would create a QList and then pass either a copy or the reference to the worker thread. So
1) Create a QList pnp_data, in the public part of mytable
2) Fill all data using a for loop as follows.
3) Create another QList pnp_data or a QList *pnp_data (if you want to use a copy or a pointer)
4) Then just pass either a copy or a reference to the worker thread.
Then it should look like this:
mytable.h source code
public: QList<pnp_com_info> pnp_data;
mytable.cpp source code
void mytable::prepare_data(){
// get table row count
int rowCount = ui->my_table_view->rowCount();
// HERE YOU LOAD ALL THE VALUES TO THE LIST
for(int i = 0; i<rowCount; i++){
pnp_com_info itemToInsert;
//FILL HERE THE itemToInsert
//Insert the item inside the list.
pnp_data.append(itemToInsert);
}
// PROBLEM : how to pass pnp_data structure to thread side ?
// Either pass it as a copy
RunJobThread->pnp_data = pnp_data;
//or as a reference
QList<pnp_com_info> *pnpDataPointer = &pnp_data;
RunJobThread->pnp_data_reference = pnpDataPointer;
// start QT thread
RunJobThread->start();
// std:: thread experiment
// std::stdthreadtest(pnp_data,rowCount);
}
run_job_thread.h source code
#ifndef RUN_JOB_THREAD_H
#define RUN_JOB_THREAD_H
#include <QObject>
#include <QThread>
class run_job_thread : public QThread
{
Q_OBJECT
public:
run_job_thread();
void run();
struct pnp_com_info_thread{
QString com_name = "";
int x = 0;
int y = 0;
int angle = 0;
bool status = false;
};
QList<pnp_com_info> pnp_data; //This one if you create a copy
QList<pnp_com_info> *pnp_data_reference; //This if you want a pointer
bool Stop; // bool to stop the job
signals:
void select_row_of_table_signal(int);
public slots:
};
#endif // RUN_JOB_THREAD_H
I hope this helps.
First, don't subclass QThread to create a worker - re-read How To Really, Truly Use QThreads; The Full Explanation by Maya Posch. You will find it much more manageable to create a worker object and connect the threads started() to your worker's main method, and the worker's signals to the thread's quit() and deleteLater().
Then, it should be much more straightforward to pass your data to the worker before it's moved to the thread, or to use a signal connection if it needs to be passed when the worker is running (remember to register your structure with the meta-object system for that).

Overridden virtual function not called from thread

I am writing a base class to manage threads. The idea is to allow the thread function to be overridden in child class while the base class manages thread life cycle. I ran into a strange behavior which I don't understand - it seems that the virtual function mechanism does not work when the call is made from a thread. To illustrate my problem, I reduced my code to the following:
#include <iostream>
#include <thread>
using namespace std;
struct B
{
thread t;
void thread_func_non_virt()
{
thread_func();
}
virtual void thread_func()
{
cout << "B::thread_func\n";
}
B(): t(thread(&B::thread_func_non_virt, this)) { }
void join() { t.join(); }
};
struct C : B
{
virtual void thread_func() override
{
cout << "C::thread_func\n";
}
};
int main()
{
C c; // output is "B::thread_func" but "C::thread_func" is expected
c.join();
c.thread_func_non_virt(); // output "C::thread_func" as expected
}
I tried with both Visual studio 2017 and g++ 5.4 (Ubuntu 16) and found the behavior is consistent. Can someone point out where I got wrong?
== UPDATE ==
Based on Igor's answer, I moved the thread creation out of the constructor into a separate method and calling that method after the constructor and got the desired behavior.
Your program exhibits undefined behavior. There's a race on *this between thread_func and C's (implicitly defined) constructor.
#include <iostream>
#include <thread>
using namespace std;
struct B
{
thread t;
void thread_func_non_virt()
{
thread_func();
}
virtual void thread_func()
{
cout << "B::thread_func\n";
}
B(B*ptr): t(thread(&B::thread_func_non_virt, ptr))
{
}
void join() { t.join(); }
};
struct C:public B
{
C():B(this){}
virtual void thread_func() override
{
cout << "C::thread_func\n";
}
};
int main()
{
C c; // "C::thread_func" is expected as expected
c.join();
c.thread_func_non_virt(); // output "C::thread_func" as expected
}

C++ Qt: Redirect cout from a thread to emit a signal

In a single thread, I have this beautiful class that redirects all cout output to a QTextEdit
#include <iostream>
#include <streambuf>
#include <string>
#include <QScrollBar>
#include "QTextEdit"
#include "QDateTime"
class ThreadLogStream : public std::basic_streambuf<char>, QObject
{
Q_OBJECT
public:
ThreadLogStream(std::ostream &stream) : m_stream(stream)
{
m_old_buf = stream.rdbuf();
stream.rdbuf(this);
}
~ThreadLogStream()
{
// output anything that is left
if (!m_string.empty())
{
log_window->append(m_string.c_str());
}
m_stream.rdbuf(m_old_buf);
}
protected:
virtual int_type overflow(int_type v)
{
if (v == '\n')
{
log_window->append(m_string.c_str());
m_string.erase(m_string.begin(), m_string.end());
}
else
m_string += v;
return v;
}
virtual std::streamsize xsputn(const char *p, std::streamsize n)
{
m_string.append(p, p + n);
long pos = 0;
while (pos != static_cast<long>(std::string::npos))
{
pos = m_string.find('\n');
if (pos != static_cast<long>(std::string::npos))
{
std::string tmp(m_string.begin(), m_string.begin() + pos);
log_window->append(tmp.c_str());
m_string.erase(m_string.begin(), m_string.begin() + pos + 1);
}
}
return n;
}
private:
std::ostream &m_stream;
std::streambuf *m_old_buf;
std::string m_string;
QTextEdit* log_window;
};
However, this doesn't work if ANY thread (QThread) is initiated with a cout. This is because all pointers are messed up, and one has to use signals and slots for allowing transfer of data between the sub-thread and the main thread.
I would like to modify this class to emit a signal rather than write to a text file. This requires that this class becomes a Q_OBJECT and be inherited from one. I tried to inherit from QObject in addition to std::basic_streambuf<char> and added Q_OBJECT macro in the body but it didn't compile.
Could you please help me to achieve this? What should I do to get this class to emit signals that I can connect to and that are thread safe?
For those who need the full "working" answer, here it's. I just copied it because #GraemeRock asked for it.
#ifndef ThreadLogStream_H
#define ThreadLogStream_H
#include <iostream>
#include <streambuf>
#include <string>
#include <QScrollBar>
#include "QTextEdit"
#include "QDateTime"
class ThreadLogStream : public QObject, public std::basic_streambuf<char>
{
Q_OBJECT
public:
ThreadLogStream(std::ostream &stream) : m_stream(stream)
{
m_old_buf = stream.rdbuf();
stream.rdbuf(this);
}
~ThreadLogStream()
{
// output anything that is left
if (!m_string.empty())
{
emit sendLogString(QString::fromStdString(m_string));
}
m_stream.rdbuf(m_old_buf);
}
protected:
virtual int_type overflow(int_type v)
{
if (v == '\n')
{
emit sendLogString(QString::fromStdString(m_string));
m_string.erase(m_string.begin(), m_string.end());
}
else
m_string += v;
return v;
}
virtual std::streamsize xsputn(const char *p, std::streamsize n)
{
m_string.append(p, p + n);
long pos = 0;
while (pos != static_cast<long>(std::string::npos))
{
pos = static_cast<long>(m_string.find('\n'));
if (pos != static_cast<long>(std::string::npos))
{
std::string tmp(m_string.begin(), m_string.begin() + pos);
emit sendLogString(QString::fromStdString(tmp));
m_string.erase(m_string.begin(), m_string.begin() + pos + 1);
}
}
return n;
}
private:
std::ostream &m_stream;
std::streambuf *m_old_buf;
std::string m_string;
signals:
void sendLogString(const QString& str);
};
#endif // ThreadLogStream_H
The derivation needs to happen QObject-first:
class LogStream : public QObject, std::basic_streambuf<char> {
Q_OBJECT
...
};
...
If the goal was to minimally modify your code, there's a simpler way. You don't need to inherit QObject to emit signals iff you know exactly what slots the signals are going to. All you need to do is to invoke the slot in a thread safe way:
QMetaObject::invokeMethod(log_window, "append", Qt::QueuedConnection,
Q_ARG(QString, tmp.c_str()));
To speed things up, you can cache the method so that it doesn't have to be looked up every time:
class LogStream ... {
QPointer<QTextEdit> m_logWindow;
QMetaMethod m_append;
LogStream::LogStream(...) :
m_logWindow(...),
m_append(m_logWindow->metaObject()->method(
m_logWindow->metaObject()->indexOfSlot("append(QString)") )) {
...
}
};
You can then invoke it more efficiently:
m_append.invoke(m_logWindow, Qt::QueuedConnection, Q_ARG(QString, tmp.c_str()));
Finally, whenever you're holding pointers to objects whose lifetimes are not under your control, it's helpful to use QPointer since it never dangles. A QPointer resets itself to 0 when the pointed-to object gets destructed. It will at least prevent you from dereferencing a dangling pointer, since it never dangles.

Issue with thread_specific_ptr data deletion at thread end

I use the thread local storage with boost.
I have a global variable :
boost::thread_specific_ptr<MyDataClass> p_timeline_ctx;
and I have the following class, which encapsulates a boost::thread object and contains an additionnal data object :
class MyThread {
private :
boost::thread t;
MyDataClass d;
public :
MyThread():c() {}
void start(void) {
ptr.reset(this->d);
this->t = boost::thread(&MyThread::worker, this);
}
void worker(void) {
// do something
}
};
I do not get any error when compiling. But on runtime, when the worker function exits and the thread ends, I get a "glibc ... free ... invalid pointer" error.
I guess this comes from the fact that, according to the boost doc, the thread_specific_ptr tries to delete the object it points to when threads end. But I do not see how to solve the problem.
The thread specific pointer takes ownership. You could reset it:
p_timeline_ctx.reset(0);
or intialize it with a deep copy in the first place:
ptr.reset(new MyDataStruct(d));
However, you'd be far better off just passing the reference as an argument to the thread pointer.
In fact, the worker is already an instance member function, so, why do you need a thread-specific copy of this:
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <iostream>
struct MyDataClass { };
class MyThread {
private :
boost::thread t;
MyDataClass d;
public :
MyThread(): d() {}
void start(void) {
t = boost::thread(&MyThread::worker, this);
}
void worker() {
// just use this->d here
}
};
int main()
{
}
Or using a static thread function:
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <iostream>
struct MyDataClass { };
class MyThread {
private :
boost::thread t;
MyDataClass d;
public :
MyThread(): d() {}
void start(void) {
t = boost::thread(&MyThread::worker, boost::ref(d));
}
static void worker(MyDataClass&) {
// do something
}
};
int main()
{
}

error C2064: term does not evaluate to a function taking 0 arguments thread.hpp(60)

I'm creating c++ game server. The server creates many objects monster, and every monster should have its thread with specific function.
I get error :
error C2064: term does not evaluate to a function taking 0 arguments
thread.hpp(60) : while compiling class template member function 'void
boost::detail::thread_data<F>::run(void)'
monster.cpp:
#include "monster.h"
monster::monster(string temp_mob_name)
{
//New login monster
mob_name = temp_mob_name;
x=rand() % 1000;
y=rand() % 1000;
boost::thread make_thread(&monster::mob_engine);
}
monster::~monster()
{
//Destructor
}
void monster::mob_engine()
{
while(true)
{
Sleep(100);
cout<< "Monster name"<<mob_name<<endl;
}
}
monster.h:
#ifndef _H_MONSTER_
#define _H_MONSTER_
//Additional include dependancies
#include <iostream>
#include <string>
#include "boost/thread.hpp"
using namespace std;
class monster
{
public:
//Functions
monster(string temp_mob_name);
~monster();
//Custom defined functions
void mob_engine();
int x;
int y;
};
//Include protection
#endif
mob_engine is a non-static member function, so it has an implicit this argument.
Try this:
boost::thread make_thread(boost::bind(&monster::mob_engine, this));
According to this similar question boost:thread - compiler error you can even avoid using bind by simply writing:
boost::thread make_thread(&monster::mob_engine, this);
Also, you will probably want to declare a boost::thread member variable to keep a reference to the thread.

Resources