2016-08-06 56 views
-1

我的問題是無效的轉換函數指針到成員函數。 當coap_handler成員函數是靜態的時候,一切都很好。 CoapClient的實例不能是靜態的和全局的。我想從coap_handler()中移除靜態。如何做到這一點?由於無效的轉換函數指針到成員函數

class CoapClient{ 
... 
void connect(){  
mg_connect(&mgr, address.c_str(), coap_handler); 
} 

static void coap_handler(struct mg_connection *nc, int ev, void *p) { 
... 

} 
}; 

//////簽名mg_connect function

struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address, 
           mg_event_handler_t callback); 

//////簽名mg_event_handler_t

回調函數(事件處理程序)的原型。必須由用戶定義。 Mongoose調用事件處理程序,傳遞下面定義的事件。

typedef void (*mg_event_handler_t)(struct mg_connection *, int ev, void *); 
+0

你不能?成員函數指針需要有一個實例來調用它們。 –

+0

連接方法在CoapClient類的構造函數中調用。 –

+0

發佈一個[MCVE],可以真實地展示您的問題。 –

回答

0

您不能將成員函數指針轉換爲常規函數指針,您需要一個「蹦牀」。

假設每個CoapClient擁有它自己的mg_mgr,你可以在施工期間爲它提供一個指向類實例:

struct CoapClient { 
    mg_mgr mgr_; // _ suffix to annotate member variable 
    std::string address_; 

    CoapClient() { 
     mg_mgr_init(&mgr_, self); // `self` is mg_mgr's userData. 
    } 

    // We need a regular/static function to pass to the handler, 
    // this is the trampoline: 
    static connect_handler(mg_connection* conn, int ev, void *userData) { 
     auto instance = static_cast<CoapClient>(userData); 
     userData->onConnect(conn, ev); 
    } 

    void onConnect(mg_connection* conn, int ev); 

    void connect() { 
     mg_connect(&mgr_, address_.c_str(), connect_handler); 
    } 
} 

或者,我們可以使用lambda熬它歸結爲:

struct CoapClient { 
    mg_mgr mgr_; // _ suffix to annotate member variable 
    std::string address_; 

    CoapClient() { 
     mg_mgr_init(&mgr_, self); // `self` is mg_mgr's userData. 
    } 

    void onConnect(mg_connection* conn, int ev); 

    void connect() { 
     mg_connect(&mgr_, address_.c_str(), [](mg_connection* conn, int ev, void *ud) { 
      static_cast<CoapClient*>(ud)->onConnect(conn, ev); 
     }); 
    } 
}