codeLover
codeLover

Reputation: 3810

What is the use of callback function in C++ ?

Hi I am very curious to know what is the usage of callback functions. Can anyone kindly explain it with a simple example please.

In my project I observe a particular CallBack function is suddenly called by some function which is indicated as User.dll!546383c() in the call stack.

I am really confused that who is calling this callback and when does it happen.

Call stack looks good till a point (i.e Function A() calling B() calling C() etc....) and suddenly something happens and Some function in User.dll calls this call back. SO I loose track of the functions.

Can anyone kindly explain with an example. Thanks in advance.

Upvotes: 2

Views: 3798

Answers (2)

neo
neo

Reputation: 425

Simply, Callbacks are like function pointers, used to configure one function to report back to (call back) another function in the application. Example, With this approach, one can handle events such as button-clicking, mouse-moving, menu-selecting, and general bidirectional communications between two entities in memory.

so the one who triggers the callback may be a user input or any other communication events raised.

Upvotes: 1

Tony Delroy
Tony Delroy

Reputation: 106236

Hi I am very curious to know what is the usage of callback functions. Can anyone kindly explain it with a simple example please.

There's not a lot to say about this. Callbacks are a mechanism for some library or system code to let client/application code handle an event. For example, you might have a callback related to:

  • expiry of some timer/alarm
  • an I/O event, such as completion of reading or writing from files, network, keyboard/console etc., or even a change to the ability of the program to read or write (based on buffer size limitations), or new/lost connections
  • completion of some asynchronous processing (e.g. another thread doing some calculations)
  • an unexpected error in some asynchronous processing
  • an opportunity to guide some process while it's in a particular state (e.g. make a decision about whether to accept a particular client, after which the caller will either disconnect or begin some asynchronous client handling)

Why user.dll happens to be giving you a callback - who knows? You haven't told us anything about your program or what it's doing.

At a logical level, a callback may not actually be dispatched in your thread until your thread checks (maybe even blocks to wait for) enqueued messages, or a callback may interrupt whatever your thread is doing to do some separate processing. The former is common when the events are created by other parts of your C++ program, the latter common for Operating-System and hardware callbacks (e.g. a "signal" on Linux/UNIX).

Upvotes: 2

Related Questions