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

Use std::function to define callbacks? #142

Open
Jopand opened this issue Apr 28, 2021 · 4 comments
Open

Use std::function to define callbacks? #142

Jopand opened this issue Apr 28, 2021 · 4 comments

Comments

@Jopand
Copy link

Jopand commented Apr 28, 2021

typedef void (* PAdsNotificationFuncExConst)(const AmsAddr* pAddr, const AdsNotificationHeader* pNotification,

The current callback typedef is a bit "stiff". I have to provide a static method (correct me if I'm wrong) or a lambda with nothing piped in. If I pipe anything into the callback lambda, I get compiler errors.

If it was replaced with std::function it would be more flexible. I could use non-static methods or lambdas where I can pipe data into it.

The new suggested callback typedef would then be:
typedef std::function<void(const AmsAddr* pAddr, const AdsNotificationHeader* pNotification, uint32_t hUser)> PAdsNotificationFuncExConst;

@marcus-sonestedt
Copy link
Contributor

Agree. I made a static function and then a dispatcher via a std::unordered_map from uint32_t to my std::functions.

if uint32_t had been uint64_t, or void*, it'd be a bit easier as you could use a pointer to the function or something, but having the full std::function would be even better, then we could use lambdas as well.

@Sssswl
Copy link

Sssswl commented Apr 6, 2022

Hi, could you please elaborate or provide a code snippet to show how this could be done? Did you made the dispatcher a static function and pass it as the callback?

I'm having the same issue. I tried to pass in the class pointer as uint32_t, but then found out that the pointer is 64 bit long and the callback could not find my class member variables because the pointer got shortened.

@stefanbesler
Copy link

stefanbesler commented Apr 6, 2022

@Sssswl use a map instance like std::map<uint32_t, SomeClass*> callbacks.
When you register the notification you generate a hash (or simply an increasing number), which you pass as hUser and store it in the map callbacks[hash] = &yourclass

For a code snippet see a little wrapper that I made some time ago for Qt/QML

I hope that is helpful for you

@Sssswl
Copy link

Sssswl commented Apr 6, 2022

@stefanbesler Your code was very helpful! My main problem was just where to put this std::map. I didn't realize I could also make it static. Everything's working now.

Thank you very much for your help!

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

No branches or pull requests

4 participants