Debian Codegraph @

third_party/rust/block/README.md

raw
1 Rust interface for Apple's C language extension of blocks.
2
3 For more information on the specifics of the block implementation, see
4 Clang's documentation: http://clang.llvm.org/docs/Block-ABI-Apple.html
5
6 ## Invoking blocks
7
8 The `Block` struct is used for invoking blocks from Objective-C. For example,
9 consider this Objective-C function:
10
11 ``` objc
12 int32_t sum(int32_t (^block)(int32_t, int32_t)) {
13 return block(5, 8);
14 }
15 ```
16
17 We could write it in Rust as the following:
18
19 ``` rust
20 unsafe fn sum(block: &Block<(i32, i32), i32>) -> i32 {
21 block.call((5, 8))
22 }
23 ```
24
25 Note the extra parentheses in the `call` method, since the arguments must be
26 passed as a tuple.
27
28 ## Creating blocks
29
30 Creating a block to pass to Objective-C can be done with the `ConcreteBlock`
31 struct. For example, to create a block that adds two `i32`s, we could write:
32
33 ``` rust
34 let block = ConcreteBlock::new(|a: i32, b: i32| a + b);
35 let block = block.copy();
36 assert!(unsafe { block.call((5, 8)) } == 13);
37 ```
38
39 It is important to copy your block to the heap (with the `copy` method) before
40 passing it to Objective-C; this is because our `ConcreteBlock` is only meant
41 to be copied once, and we can enforce this in Rust, but if Objective-C code
42 were to copy it twice we could have a double free.