[Libwebsockets] callback pointer

andy at warmcat.com andy at warmcat.com
Sat May 15 04:25:24 CEST 2021



On May 14, 2021 7:23:15 PM UTC, Trey Weaver <treyweaver at fastmail.net> wrote:
>What is the best way to pass a pointer to a callback?
>
>I want to set up a pointer to a class (i'm using c++) an retrieve that
>pointer when I get a callback.
>
>I tried setting up the *protocols[0].user = this*; 
>
>And I tried:
>*lws_context_creation_info.user = this;*
>
>And then looked at the *user data on the call back, but the pointers
>did not match.
>
>I then looked at using: 
>*lws_client_connect_info.opaque_user_data = this.*
>and then use in the call back 
>*ws_get_opaque_user_data(wsi);*
>
>This worked ok, and I probably could live with it but I miss the

Yes, for a wsi c++ object binding on client wsi, the opaque pointer has the right scope.  The other choices are used for binding other scopes, eg, similar opaque pointers available per context, or per vhost.

>pointer for the first three messages when I set up the context and

The protocol callback receives a lot of callbacks where the subject is one of your wsis.  But it also receives several kinds of callback where there's no wsi related to the action, eg, PROTOCOL_INIT coming before you had a chance to create any wsi.  In these cases, lws passes a fakewsi prepared with key pointers like to the context.

So although you can recover and cast the wsi's opaque pointer to your c++ object from the incoming wsi unconditionally, it will sometimes not be one of your wsi, and it will be NULL then.  So you cannot dereference it unconditionally, eg before switch (reason).

This works out if you just dereference it in the callback reason handlers that you care about, where your wsi is definitely the subject, like RX or WRITEABLE.

-Andy



More information about the Libwebsockets mailing list