Search code examples
c++websocketcpprest-sdk

Callbacks to decouple API usage


I'm trying to create a simple static class library to decouple WebSocket usage from the rest of my code. Creating this will allow me to easily switch the WebSocket library (I'm currently using cpprestsdk) without the need to change my code (or its underlying logic), based on benchmark tests that will be performed in the near future.

In the below code, I'm trying to have a callback for openConnection():

class WebSocket
{
    websocket_callback_client wsClient;     

    void openConnection(void (*ptr)(std::string response),std::string _url)
    {
        wsClient.connect(_url).then([](){ });

        wsClient.set_message_handler([](websocket_incoming_message msg)
        {
            ptr(msg.extract_string().get());

        });
    }
};

This looks obviously wrong, as the compiler throws an error:

'ptr' is not captured

But this is what I'm trying to achieve.

How can I do this?


Solution

  • As the compiler says, you have not captured ptr in the lambda that is trying to use it. That is because you are setting the lambda's capture list to be empty. You need to specify ptr in the lambda's capture list:

    wsClient.set_message_handler(
        [ptr](websocket_incoming_message msg)
        {
            ptr(msg.extract_string().get());
        });
    

    Or, let the lambda figure out for itself that ptr needs to be captured:

    wsClient.set_message_handler(
        [=](websocket_incoming_message msg)
        {
            ptr(msg.extract_string().get());
        });