Creating the code

The code for this part is in Chapter 14/firstexample.

When we are dealing with code from outside our application, we need to be able to tell the compiler something akin to "Hey look, build this code and just leave a hook to something that may or may not exist and that may or may not take these parameters but that will return something hopefully." It's like handing a blank check to a fraudster with your signature on and hoping they won't write something in and cash it!

In Rust, we do this by using the link directive and enclosing the function in an extern block. The code inside the extern calls the function held within the library. It must be the same as the name of the function within the library:

[link(name="mathlib")] 
extern 
 { 
     fn add_two_int_numbers(a: i32, b: i32) -> i32; 
} 

This code is then accessed using the following:

fn main() 
 { 
    let ans = unsafe { add_two_int_numbers(10,20) }; 
    println!("10 + 20 = {}", ans); 
} 
..................Content has been hidden....................

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