Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calback functions (or Rotary object) should have a void* argument #48

Open
homedatadev opened this issue Jan 4, 2024 · 3 comments
Open
Assignees

Comments

@homedatadev
Copy link

Most callback functions take a void* argument to provide some custom context. When you cannot do some lambda/closure functions like in Python, this is the way to work around it.

In my case, it would allow me to pass the pointer of the object that owns the Rotary object (and other things)

@LennartHennigs
Copy link
Owner

Hey,
thank you for your comment. I will take a look at your suggestion.

Cheers
l.

@homedatadev
Copy link
Author

homedatadev commented Jan 9, 2024 via email

@NSBum
Copy link

NSBum commented Apr 2, 2024

@homedatadev I looked at your fork - but your changes don't seem to have made it into your fork of the repo. Can you push your changes back to your fork, so we can see what you've done? I agree that the ability to pass a (void *) context object would be useful and more in line with C design patterns. Is it just something like this (purposefully incomplete here...):

/* in the public member declaration... */
using CallbackFunction = void (*)(ESPRotary&, void*);

void setChangedHandler(CallbackFunction f, void *context);
void setRightRotationHandler(CallbackFunction f, void *context);
void setLeftRotationHandler(CallbackFunction f, void *context);

And we have to retain the context:

void setChangedHandler(CallbackFunction f, void* context) {
   change_cb = f;
   change_cb_context = context;
}

Then in the implementation of _callCallback() we account for the context:

/* just for example... */
void ESPRotary::_callCallback(CallbackFunction callback, void* context) {
  if (callback != NULL) callback(*this, context);
}

And changes to you the callback itself:

typedef struct {
   uint16_t foo;
   uint8_t bar;
} example_context_t;

void rotate_callback(ESPRotary& r, void* context) {
  // Cast the context pointer back to the appropriate type
  example_context_t *data = static_cast<example_context_t *>(context);
  ESP_LOGI("my_module", "foo from context = %d", datafoo);
}

// Setting the callback with the context
example_context_t ctx;
ctx.foo = 65535;
ctx.bar = 127;
ro.setChangedHandler(rotate_callback, &ctx);

etc.

Happy to fork it too and send a PR, too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants