Targeting synchronous callbacks

Synchronous callbacks are the simplest to target, as they are normally always on the same thread. Therefore, we don't have to deal with the code being more unsafe than usual, which is normally the case with asynchronous callbacks.

The code for this part is in Chapter 14/synccallback. Instructions for building on Linux, macOS, and Windows are included in the source examples.

Let's deal with the Rust side of the code first. Here, we have three parts:

  1. The function for the callback itself:
extern fn my_callback(percent: i32) 
 { 
     println!("Process is now {}% complete", percent); 
} 
  1. The calls to the external code:
[link(name="external_lib")] 
extern 
 { 
     fn register_callback(call: extern fn(i32)) -> i32; 
     fn do_callback_trigger(); 
} 
  1. Fire off the code:
fn main() 
 { 
    unsafe 
 { 
         register_callback(my_callback); 
         do_callback_trigger(); 
    } 
} 

register_callback(my_callback) and fn register_callback(call: extern fn(i32)) ->→ i32; may look strange at first glance. In a normal function call, the parameters within the braces are passed into the receiving function, which then does something with them.

Here, we are passing a function as the parameter, which we really can't do (or at least shouldn't). Callbacks though are different, as the function is by virtue of the extern modifier counted as a pointer that takes the returned value from the external library as its own parameter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset