2016-08-06 57 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); 
     }); 
    } 
}