C++ freeRTOS Task, invalid use of non-static member function

雨燕双飞 提交于 2021-02-07 09:13:51

问题


Where is the Problem?

void MyClass::task(void *pvParameter){
     while(1){
         this->update();
     }
}

void MyClass::startTask(){
    xTaskCreate(this->task, "Task", 2048, NULL, 5, NULL);
}

But, I get this:

error: invalid use of non-static member function

I cannot find any useful doc to check where is the mistake,
but i think that should be something like: (C++11's std::thread) e.g.:

xTaskCreate(&MyClass::task, "Task", 2048, (void*)this, 5, NULL);

solution that works for me:

void MyClass::task(){
    while(1){
        this->update();
    }
}

static void MyClass::startTaskImpl(void* _this){
    static_cast<MyClass*>(_this)->task();
}

void MyClass::startTask(){
    xTaskCreate(this->startTaskImpl, "Task", 2048, this, 5, NULL);
}

回答1:


I use this pattern with a wrapper function for instanciating pthread with non-static member functions. The function called in xTask is a static member function, calling the task function using void* pointer. MyClass.hpp :

class MyClass {
    public:
        MyClass() {}
        ~MyClass() {}
    private:
        void update();
        void task();
        static void startTaskImpl(void*);
        void startTask();
 }

MyClass.cpp :

void MyClass::task(){
     while(1){
         this->update();
     }
}

void MyClass::startTaskImpl(void* _this){
    (MyClass*)_this->task();
}
void MyClass::startTask(){
    xTaskCreate(this->startTaskImpl, "Task", 2048, this, 5, NULL);
}



回答2:


According to this FreeRTOS official thread, you can write wrapper function to achieve this.



来源:https://stackoverflow.com/questions/45831114/c-freertos-task-invalid-use-of-non-static-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!