Pointers to member functions within the same class (C++)? - c++

I am writing a program to control a auto home brewing system on an Arduino Mega micro controller (written in C/C++). In short, what the program is doing is there is a C# application which periodically sends messages through USB to the micro controller. There is then a messaging interface which I wrote which reads the message, and forwards it to whichever component the message is for. Each message is 16 bytes long, the first 4 is a transaction code, and the last 12 is for data. Now, I read in the message and forward to it to my StateController class. It comes in from the InboundMessage function. What I am trying to do is I have a struct (defined in StateController.h) which contains the transaction code and pointer to a member function within StateController. I defined a QueueList (just a simple linked list library), and pushed a bunch of these structs into it. What I would like to do is then when a message comes into the inboundMessage function, i would like to loop through the linked list until I find a transaction code which matches, and then call the member function which is for that message, passing it the data in the message.
I think I have everything initialized correctly, but here is the problem. When I try and compile I get an error saying "func does not exist in this scope". I have looked all over for a solution to this, but can not find one. My codes is below
StateController.cpp
StateController::StateController(){
currentState = Idle;
prevState = Idle;
lastRunState = Idle;
txnTable.push((txnRow){MSG_BURN, &StateController::BURNprocessor});
txnTable.push((txnRow){MSG_MANE, &StateController::MANEprocessor});
txnTable.push((txnRow){MSG_MAND, &StateController::MANDprocessor});
txnTable.push((txnRow){MSG_PUMP, &StateController::PUMPprocessor});
txnTable.push((txnRow){MSG_STAT, &StateController::STATprocessor});
txnTable.push((txnRow){MSG_SYNC, &StateController::SYNCprocessor});
txnTable.push((txnRow){MSG_VALV, &StateController::VALVprocessor});
}
void StateController::inboundMessage(GenericMessage msg){
// Read transaction code and do what needs to be done for it
for (int x = 0; x < txnTable.count(); x++)
{
if (compareCharArr(msg.code, txnTable[x].code, TXN_CODE_LEN) == true)
{
(txnTable[x].*func)(msg.data);
break;
}
}
}
StateController.h
class StateController{
// Public functions
public:
// Constructor
StateController();
// State Controller message handeler
void inboundMessage(GenericMessage msg);
// Main state machine
void doWork();
// Private Members
private:
// Hardware interface
HardwareInterface hardwareIntf;
// Current state holder
StateControllerStates currentState;
// Preveous State
StateControllerStates prevState;
// Last run state
StateControllerStates lastRunState;
// BURN Message Processor
void BURNprocessor(char data[]);
// MANE Message Processor
void MANEprocessor(char data[]);
// MAND Message Processor
void MANDprocessor(char data[]);
// PUMP Message Processor
void PUMPprocessor(char data[]);
//STAT Message Processor
void STATprocessor(char data[]);
// SYNC Message Processor
void SYNCprocessor(char data[]);
// VALV Message Processor
void VALVprocessor(char data[]);
void primePumps();
// Check the value of two sensors given the window
int checkSensorWindow(int newSensor, int prevSensor, int window);
struct txnRow{
char code[TXN_CODE_LEN + 1];
void (StateController::*func)(char[]);
};
QueueList<txnRow> txnTable;
};
Any idea what is wrong?

func is just a normal member of txnRow so you access it with ., not .*, e.g. txnTable[x].func.
To call this member function on, say, this, you would do something like:
(this->*(txnTable[x].func))(msg.data);

Related

Readable node stream to native c++ addon InputStream

Conceptually what I'm trying to do is very simple. I have a Readable stream in node, and I'm passing that to a native c++ addon where I want to connect that to an IInputStream.
The native library that I'm using works like many c++ (or Java) streaming interfaces that I've seen. The library provides an IInputStream interface (technically an abstract class), which I inherit from and override the virtual functions. Looks like this:
class JsReadable2InputStream : public IInputStream {
public:
// Constructor takes a js v8 object, makes a stream out of it
JsReadable2InputStream(const v8::Local<v8::Object>& streamObj);
~JsReadable2InputStream();
/**
* Blocking read. Blocks until the requested amount of data has been read. However,
* if the stream reaches its end before the requested amount of bytes has been read
* it returns the number of bytes read thus far.
*
* #param begin memory into which read data is copied
* #param byteCount the requested number of bytes
* #return the number of bytes actually read. Is less than bytesCount iff
* end of stream has been reached.
*/
virtual int read(char* begin, const int byteCount) override;
virtual int available() const override;
virtual bool isActive() const override;
virtual void close() override;
private:
Nan::Persistent<v8::Object> _stream;
bool _active;
JsEventLoopSync _evtLoop;
};
Of these functions, the important one here is read. The native library will call this function when it wants more data, and the function must block until it is able to return the requested data (or the stream ends). Here's my implementation of read:
int JsReadable2InputStream::read(char* begin, const int byteCount) {
if (!this->_active) { return 0; }
int read = -1;
while (read < 0 && this->_active) {
this->_evtLoop.invoke(
(voidLambda)[this,&read,begin,byteCount](){
v8::Local<v8::Object> stream = Nan::New(this->_stream);
const v8::Local<v8::Function> readFn = Nan::To<v8::Function>(Nan::Get(stream, JS_STR("read")).ToLocalChecked()).ToLocalChecked();
v8::Local<v8::Value> argv[] = { Nan::New<v8::Number>(byteCount) };
v8::Local<v8::Value> result = Nan::Call(readFn, stream, 1, argv).ToLocalChecked();
if (result->IsNull()) {
// Somewhat hacky/brittle way to check if stream has ended, but it's the only option
v8::Local<v8::Object> readableState = Nan::To<v8::Object>(Nan::Get(stream, JS_STR("_readableState")).ToLocalChecked()).ToLocalChecked();
if (Nan::To<bool>(Nan::Get(readableState, JS_STR("ended")).ToLocalChecked()).ToChecked()) {
// End of stream, all data has been read
this->_active = false;
read = 0;
return;
}
// Not enough data available, but stream is still open.
// Set a flag for the c++ thread to go to sleep
// This is the case that it gets stuck in
read = -1;
return;
}
v8::Local<v8::Object> bufferObj = Nan::To<v8::Object>(result).ToLocalChecked();
int len = Nan::To<int32_t>(Nan::Get(bufferObj, JS_STR("length")).ToLocalChecked()).ToChecked();
char* buffer = node::Buffer::Data(bufferObj);
if (len < byteCount) {
this->_active = false;
}
// copy the data out of the buffer
if (len > 0) {
std::memcpy(begin, buffer, len);
}
read = len;
}
);
if (read < 0) {
// Give js a chance to read more data
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
return read;
}
The idea is, the c++ code keeps a reference to the node stream object. When the native code wants to read, it has to synchronize with the node event loop, then attempt to invoke read on the node stream. If the node stream returns null, this indicates that the data isn't ready, so the native thread sleeps, giving the node event loop thread a chance to run and fill its buffers.
This solution works perfectly for a single stream, or even 2 or 3 streams running in parallel. Then for some reason when I hit the magical number of 4+ parallel streams, this totally deadlocks. None of the streams can successfully read any bytes at all. The above while loop runs infinitely, with the call into the node stream returning null every time.
It is behaving as though node is getting starved, and the streams never get a chance to populate with data. However, I've tried adjusting the sleep duration (to much larger values, and randomized values) and that had no effect. It is also clear that the event loop continues to run, since my lambda function continues to get executed there (I put some printfs inside to confirm this).
Just in case it might be relevant (I don't think it is), I'm also including my implementation of JsEventLoopSync. This uses libuv to schedule a lambda to be executed on the node event loop. It is designed such that only one can be scheduled at a time, and other invocations must wait until the first completes.
#include <nan.h>
#include <functional>
// simplified type declarations for the lambda functions
using voidLambda = std::function<void ()>;
// Synchronize with the node v8 event loop. Invokes a lambda function on the event loop, where access to js objects is safe.
// Blocks execution of the invoking thread until execution of the lambda completes.
class JsEventLoopSync {
public:
JsEventLoopSync() : _destroyed(false) {
// register on the default (same as node) event loop, so that we can execute callbacks in that context
// This takes a function pointer, which only works with a static function
this->_handles = new async_handles_t();
this->_handles->inst = this;
uv_async_init(uv_default_loop(), &this->_handles->async, JsEventLoopSync::_processUvCb);
// mechanism for passing this instance through to the native uv callback
this->_handles->async.data = this->_handles;
// mutex has to be initialized
uv_mutex_init(&this->_handles->mutex);
uv_cond_init(&this->_handles->cond);
}
~JsEventLoopSync() {
uv_mutex_lock(&this->_handles->mutex);
// prevent access to deleted instance by callback
this->_destroyed = true;
uv_mutex_unlock(&this->_handles->mutex);
// NOTE: Important, this->_handles must be a dynamically allocated pointer because uv_close() is
// async, and still has a reference to it. If it were statically allocated as a class member, this
// destructor would free the memory before uv_close was done with it (leading to asserts in libuv)
uv_close(reinterpret_cast<uv_handle_t*>(&this->_handles->async), JsEventLoopSync::_asyncClose);
}
// called from the native code to invoke the function
void invoke(const voidLambda& fn) {
if (v8::Isolate::GetCurrent() != NULL) {
// Already on the event loop, process now
return fn();
}
// Need to sync with the event loop
uv_mutex_lock(&this->_handles->mutex);
if (this->_destroyed) { return; }
this->_fn = fn;
// this will invoke processUvCb, on the node event loop
uv_async_send(&this->_handles->async);
// wait for it to complete processing
uv_cond_wait(&this->_handles->cond, &this->_handles->mutex);
uv_mutex_unlock(&this->_handles->mutex);
}
private:
// pulls data out of uv's void* to call the instance method
static void _processUvCb(uv_async_t* handle) {
if (handle->data == NULL) { return; }
auto handles = static_cast<async_handles_t*>(handle->data);
handles->inst->_process();
}
inline static void _asyncClose(uv_handle_t* handle) {
auto handles = static_cast<async_handles_t*>(handle->data);
handle->data = NULL;
uv_mutex_destroy(&handles->mutex);
uv_cond_destroy(&handles->cond);
delete handles;
}
// Creates the js arguments (populated by invoking the lambda), then invokes the js function
// Invokes resultLambda on the result
// Must be run on the node event loop!
void _process() {
if (v8::Isolate::GetCurrent() == NULL) {
// This is unexpected!
throw std::logic_error("Unable to sync with node event loop for callback!");
}
uv_mutex_lock(&this->_handles->mutex);
if (this->_destroyed) { return; }
Nan::HandleScope scope; // looks unused, but this is very important
// invoke the lambda
this->_fn();
// signal that we're done
uv_cond_signal(&this->_handles->cond);
uv_mutex_unlock(&this->_handles->mutex);
}
typedef struct async_handles {
uv_mutex_t mutex;
uv_cond_t cond;
uv_async_t async;
JsEventLoopSync* inst;
} async_handles_t;
async_handles_t* _handles;
voidLambda _fn;
bool _destroyed;
};
So, what am I missing? Is there a better way to wait for the node thread to get a chance to run? Is there a totally different design pattern that would work better? Does node have some upper limit on the number of streams that it can process at once?
As it turns out, the problems that I was seeing were actually client-side limitations. Browsers (and seemingly also node) have a limit on the number of open TCP connections to the same origin. I worked around this by spawning multiple node processes to do my testing.
If anyone is trying to do something similar, the code I shared is totally viable. If I ever have some free time, I might make it into a library.

GetDlgItemText and Multithreading

So I have been trying to implement the concept of multithreading to an MFC application I am making. I used the method suggested here. It works fine but I am having an issue with using data given by the user while the thread is working.
I'll explain.
I am making a simple GUI to send and receive data over a serial port. So the data in IDC_SEND is user-input, and is then sent through the serial port. I am using the WINAPI definition of GetDlgItemText, but since the controlling function for AfxBeginThread is defined as a static function I cannot do this. So I tried ::GetDlgItemText, but that calls the CWnd definition which takes one or three or four(?) arguments.
So ::GetDlgItemText(IDC_SEND, CString text) doesn't work. This problem continues for SetDlgItemText too.
I have tried getting the data outside my controlling function, but since it is defined to return a UINT type, I cannot get the received data out.
The relevant code
void CCommTest2Dlg::OnButton()
{
THREADSTRUCT *_param = new THREADSTRUCT;
_param->_this = this;
AfxBeginThread (StartThread, _param);
}
UINT CCommTest2Dlg::StartThread(LPVOID param)
{
THREADSTRUCT* ts = (THREADSTRUCT*)param;
AfxMessageBox ("Thread is started!");
//Opened Serial Port
//Writing data from Editbox
CString text;
::GetDlgItemText(IDC_SEND,text);//********ERROR HERE!!
serial.Write(text);
//At Receiver port data is wriiten into CString a.
CString a;
::SetDlgItemText( IDC_RECV, a);//Apparently this calls the SetDlgItemText from the CWnd class, and not the Windows API that takes more than one argument.
AfxMessageBox ((LPCTSTR)a);//This works, but I need the data in the EditBox.
//Closing Ports
delete ts; //Edit 1
return 1;}
A few definitions:
static UINT StartThread (LPVOID param);
//structure for passing to the controlling function
typedef struct THREADSTRUCT
{
CCommTest2Dlg* _this;
} THREADSTRUCT;
UINT StartThread(void);
Any thoughts?
PS: Also Edit 1 at the end was added by me as I read that this implementation could result in memory leaks. Does it look like the addition might have fixed that?

Get class object pointer from inside a static method called directly

I have the following class, for example in a header:
class Uart
{
public:
Uart (int ch, int bd = 9600, bool doinit = false);
......
static void isr (void);
}
The idea is this class represents USART hardware, the same way as SPI, RTC etc and I set the address of static member isr as interrupt vector routine during runtime.
For example like this
extern "C"
{
void
Uart::isr (void)
{
if ( USART1->SR & USART_SR_RXNE) //receive
{
short c = USART2->DR;
USART1->DR = c;
USART1->SR &= ~USART_SR_RXNE;
;
}
else if ( USART1->SR & USART_SR_TC) //transfer
{
USART1->SR &= ~USART_SR_TC;
}
}
}
And set it as a interrupt vector, for example
_vectors_[USART1_IRQn + IRQ0_EX] = (word) &dbgout.isr;
So each time this "callback" routine is called by CPU I want to get access to it's "parent" object to save and/or manipulate the received data in userfriendly manner.
Is it possible at all? Maybe somehow organize the class or whatever.
The architecture is strictly 32bit (ARM, gcc)
Static methods know nothing about the object.
You need a different approach:
// Create interrupt handler method (non-static!)
void Uart::inthandler() {
// whatever is needed here
}
// Create object
Uart* p = new Uart(...);
// Create interrupt handler function
void inthandler() {
if (p != NULL) {
p->inthandler();
}
}
// Install the interrupt handler function
InstallIntHandler(IRQ, inthandler);
It's just a principle that has to be adapted to your specific environment.

Why doesn't the value of instance variable persist?

I have created a queue on the MP1Node class, and add to it from the recvCallBack method. My goal was to use this queue to send the messages after having figured out the member_list from the nodeLoopOps. However, the elements in this queue, let's call it msgQ, are getting lost as soon as checkMessages returns. I don't understand why this is happening. Is checkMessages() being executed in a new instance of the class? Why wouldn't msgQ persist and how can I make it persist?
void MP1Node::nodeLoop() {
// Check my messages
checkMessages();
// NOTE: msgQ size == 0 here
return;
}
void MP1Node::checkMessages() {
void *ptr;
int size;
...
recvCallBack((char *)ptr, size);
...
// NOTE: msgQ size == 1 here
return;
}
bool MP1Node::recvCallBack(char *data, int size ) {
...
scheduleMessage(newMsg);
...
}
void MP1Node::scheduleMessage(Message m){
msgQ.emplace(m);
}
class MP1Node {
private:
queue<Message> msgQ;
}
It's difficult to tell for sure from the skeleton code provided.
But this part is a bit suspicious:
The queue is defined to hold objects of type Message. newMsg appears to be a local variable created in method recvCallBack(). scheduleMessage() is called with that Message instance at which point the message object is enqueued. However, because the Message instance newMsg has local scope, it goes out of scope when recvCallBack() returns.
At this point I may expect the queue to contain garbage, but perhaps instead it's exhibiting as empty.

Cannot lock Qt mutex (QReadWriteLock) Access violation writing

Some background for this question is my previous question:
non-member function pointer as a callback in API to member function (it may well be irrelevant).
The callback launches a thread that writes some data. There is another thread that reads the same data, and that results in some crashes.
I just took a crash course in multi-threading (thanks SO), and here is my attempt to guarantee that the data isn't accessed by the writer and the reader at the same time. I'm using some mutex mechanism from Qt (QReadWriteLock).
#include <QSharedPointer>
#include <QReadWriteLock>
Class MyClass
{
public:
MyClass();
bool open();
float getData();
void streamCB(void* userdata);
protected:
float private_data_;
QSharedPointer<QReadWriteLock> lock_;
};
// callback wrapper from non-member C API to member function void
__stdcall streamCBWrapper(void* userdata)
{
static_cast<MyClass*>(userdata)->streamCB(userdata);
}
// constructor
MyClass::MyClass()
{
lock_ = QSharedPointer<QReadWriteLock>(new QReadWriteLock());
lock_->lockForWrite();
private_data_ = getData();
lock_->unlock();
}
// member callback
void MyClass:streamCB(void* userdata)
{
float a = getData();
lock_->lockForWrite(); //*** fails here
private_data_ = a;
lock_->unlock();
}
I have a segmentation fault while running the program. The VS debugger says Access violation writing location 0x00fedbed. on the line that I marked //*** fails here.
The lock worked in the constructor, but not in the callback.
Any idea what goes wrong? What should I look at? (and how can I refine my question)
Thanks!
Other relevant thread
Cannot access private member declared in class 'QReadWriteLock'Error 1 error C2248: 'QReadWriteLock::QReadWriteLock' (I used the QSharedPointer suggestion)
Edit 1:
The callback is set up
bool MyClass::open()
{
// stuffs
int mid = 0;
set_stream_callback(&streamCBWrapper, &mid);
// more stuffs
return true;
}
Edit 2:
Thank you for all the suggestions.
So my mistake(s) may not be due at all to the mutex, but to my lack of understanding of the API? I'm quite confused.. Here is the API doc for the set_stream_callback.
typedef void (__stdcall *STREAM_CALLBACK)(void *userdata);
/*! #brief Register a callback to be invoked when all subscribed fields have been updated
*
* #param streamCB pointer to callback function
* #param userdata pointer to private data to be passed back as argument to callback
* #return 0 if successful, error code otherwise
*/
__declspec(dllimport) int __stdcall set_stream_callback(
STREAM_CALLBACK streamCB, void *userdata);
Good example why sufficient code example is required.
If I interpret your callback syntax correctly,
set_stream_callback(&streamCBWrapper, &mid);
sets streamCBWrapper as callback function, while &mid is the pointer to userdata.
In the callback, you are actually now casting a pointer to int to MyClass, then try to access a member variable of a non-existant object.
Make sure to pass an instance of MyClass to your callback. I assume this would be this in your case.
Sounds fundamentally like a threading issue to me. Since you're using the Qt mutexing anyway, you might consider using Qt's threading mechanisms and sending signals and slots between the threads. They're pretty well documented and easy to use as long as you follow the suggestions here and here.