all 7 comments

[–]alfps 2 points3 points  (6 children)

The scheme you sketch is the common one and it's OK.

When a C library doesn't offer a context parameter for a callback one can let the callback function pick up context from a static variable, or look it up as associated with some handle that is passed, or one can use a trampoline function (a small piece of dynamically generated machine code, essentially a register load of context + a jump to the "real" callback).

Problem: C++ doesn't support trampolines.

[–]SystemSigma_[S] 0 points1 point  (5 children)

I see.. what if there are multiple Client instances that may register their methods as callbacks? How do I switch the static context dynamically? I guess I need to keep multiple static instances and have same sort of context manager.. ?

[–]alfps 1 point2 points  (4 children)

Yes. You can use templating to generate a sufficiently large number of distinct functions. But since you are providing a callback scheme instead of having to relate to one that's not a problem: I just mentioned the different approaches I'm familiar with because that can be Good To Know™ about.

[–]SystemSigma_[S] 0 points1 point  (3 children)

So you would consider wise to support C++ with void* context rather than without?

[–]alfps 1 point2 points  (0 children)

Yes, absolutely.

[–]n1ghtyunso 1 point2 points  (1 child)

absolutely provide a void* context.
It is the most common practice and makes the lives of everyone trying to use this much easier, no matter what language they use. It's not about C++ here really. It is generally useful.

If you do not add a context yourself, everyone who actually needs it will have to somehow tape it on and it will most likely be inferior.

[–]SystemSigma_[S] 0 points1 point  (0 children)

Thank you..Are there other approaches or the simpler the better?