countly-sdk-cpp icon indicating copy to clipboard operation
countly-sdk-cpp copied to clipboard

HTTPClient callback has no way of accessing non-global data

Open Zephilinox opened this issue 3 years ago • 3 comments
trafficstars

typically with callbacks a void* is passed when setting the callback, and then when something calls the callback, they will pass it that void*. this allows users to cast the void* in to whatever data they need within the callback.

without this, only static/global data is accessible from within the callback, which is quite limiting. alternatively, something like std::function or a templated function could be used instead, to allow us to pass a lambda for the callback and capture state.

Zephilinox avatar Jan 25 '22 18:01 Zephilinox

Could you please expand on this? What kind of non "static/global data" were you thinking of accessing?

The "setHTTPClient" call takes a function pointer that the SDK will use to make network requests. How were you imagining that it would look?

ArtursKadikis avatar Jan 25 '22 18:01 ArtursKadikis

sure :)

for example, if the callback needs to access an object that isn't created in the callback itself (such as a socket, or object) there's no way to have to callback be able to access it, unless it was global

typically callbacks will have a signature with a void*

void my_callback(int data, void* userdata)
{
    auto* this_is_us = static_cast<MyClass*>(userdata);
    this_is_us->call_member_function();
}

so that as a client, you can do

setCallback(&my_callback, static_cast<void*>(this));

and then later on, inside of the Countly SDK, it would do

user_callback(5, user_data);

Zephilinox avatar Jan 26 '22 16:01 Zephilinox

for a real world example, https://libusb.sourceforge.io/api-1.0/group__libusb__hotplug.html#ga5ab3955e2110a3099497a66256fb7fab libusb_hotplug_register_callback takes a void* user data pointer, which it will then use later when calling that callback

Zephilinox avatar Jan 26 '22 16:01 Zephilinox