2017-08-23 109 views
2

問題在哪裏?C++ freeRTOS任務,非法使用非靜態成員函數

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

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

但是,我得到這個:

error: invalid use of non-static member function

我無法找到任何有用的文檔來檢查哪裏出了錯誤,
但我覺得應該是這樣的:(C++ 11的STD ::線程),例如:

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

的解決方案,爲我的作品:

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); 
} 
+0

'這 - > task'無效如果'task'是一個非靜態成員函數。 – immibis

回答

3

我將此模式與包裝函數一起使用,實現具有非靜態成員函數的pthread實例。 xTask中調用的函數是一個靜態成員函數,使用void *指針調用任務函數。 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

根據FreeRTOS的官方thread,你可以編寫包裝函數來實現這一點。

相關問題