无效的转换函数指针指向成员函数

时间:2016-08-06 16:49:30

标签: c++ pointers

我的问题是将函数指针转换为成员函数无效。 当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 *);

1 个答案:

答案 0 :(得分: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);
        });
    }
}
相关问题