]> git.lizzy.rs Git - rust.git/blob - src/doc/book/ffi.md
Auto merge of #30931 - oli-obk:trans_disr_newtype, r=arielb1
[rust.git] / src / doc / book / ffi.md
1 % Foreign Function Interface
2
3 # Introduction
4
5 This guide will use the [snappy](https://github.com/google/snappy)
6 compression/decompression library as an introduction to writing bindings for
7 foreign code. Rust is currently unable to call directly into a C++ library, but
8 snappy includes a C interface (documented in
9 [`snappy-c.h`](https://github.com/google/snappy/blob/master/snappy-c.h)).
10
11 ## A note about libc
12
13 Many of these examples use [the `libc` crate][libc], which provides various
14 type definitions for C types, among other things. If you’re trying these
15 examples yourself, you’ll need to add `libc` to your `Cargo.toml`:
16
17 ```toml
18 [dependencies]
19 libc = "0.2.0"
20 ```
21
22 [libc]: https://crates.io/crates/libc
23
24 and add `extern crate libc;` to your crate root.
25
26 ## Calling foreign functions
27
28 The following is a minimal example of calling a foreign function which will
29 compile if snappy is installed:
30
31 ```no_run
32 # #![feature(libc)]
33 extern crate libc;
34 use libc::size_t;
35
36 #[link(name = "snappy")]
37 extern {
38     fn snappy_max_compressed_length(source_length: size_t) -> size_t;
39 }
40
41 fn main() {
42     let x = unsafe { snappy_max_compressed_length(100) };
43     println!("max compressed length of a 100 byte buffer: {}", x);
44 }
45 ```
46
47 The `extern` block is a list of function signatures in a foreign library, in
48 this case with the platform's C ABI. The `#[link(...)]` attribute is used to
49 instruct the linker to link against the snappy library so the symbols are
50 resolved.
51
52 Foreign functions are assumed to be unsafe so calls to them need to be wrapped
53 with `unsafe {}` as a promise to the compiler that everything contained within
54 truly is safe. C libraries often expose interfaces that aren't thread-safe, and
55 almost any function that takes a pointer argument isn't valid for all possible
56 inputs since the pointer could be dangling, and raw pointers fall outside of
57 Rust's safe memory model.
58
59 When declaring the argument types to a foreign function, the Rust compiler can
60 not check if the declaration is correct, so specifying it correctly is part of
61 keeping the binding correct at runtime.
62
63 The `extern` block can be extended to cover the entire snappy API:
64
65 ```no_run
66 # #![feature(libc)]
67 extern crate libc;
68 use libc::{c_int, size_t};
69
70 #[link(name = "snappy")]
71 extern {
72     fn snappy_compress(input: *const u8,
73                        input_length: size_t,
74                        compressed: *mut u8,
75                        compressed_length: *mut size_t) -> c_int;
76     fn snappy_uncompress(compressed: *const u8,
77                          compressed_length: size_t,
78                          uncompressed: *mut u8,
79                          uncompressed_length: *mut size_t) -> c_int;
80     fn snappy_max_compressed_length(source_length: size_t) -> size_t;
81     fn snappy_uncompressed_length(compressed: *const u8,
82                                   compressed_length: size_t,
83                                   result: *mut size_t) -> c_int;
84     fn snappy_validate_compressed_buffer(compressed: *const u8,
85                                          compressed_length: size_t) -> c_int;
86 }
87 # fn main() {}
88 ```
89
90 # Creating a safe interface
91
92 The raw C API needs to be wrapped to provide memory safety and make use of higher-level concepts
93 like vectors. A library can choose to expose only the safe, high-level interface and hide the unsafe
94 internal details.
95
96 Wrapping the functions which expect buffers involves using the `slice::raw` module to manipulate Rust
97 vectors as pointers to memory. Rust's vectors are guaranteed to be a contiguous block of memory. The
98 length is number of elements currently contained, and the capacity is the total size in elements of
99 the allocated memory. The length is less than or equal to the capacity.
100
101 ```rust
102 # #![feature(libc)]
103 # extern crate libc;
104 # use libc::{c_int, size_t};
105 # unsafe fn snappy_validate_compressed_buffer(_: *const u8, _: size_t) -> c_int { 0 }
106 # fn main() {}
107 pub fn validate_compressed_buffer(src: &[u8]) -> bool {
108     unsafe {
109         snappy_validate_compressed_buffer(src.as_ptr(), src.len() as size_t) == 0
110     }
111 }
112 ```
113
114 The `validate_compressed_buffer` wrapper above makes use of an `unsafe` block, but it makes the
115 guarantee that calling it is safe for all inputs by leaving off `unsafe` from the function
116 signature.
117
118 The `snappy_compress` and `snappy_uncompress` functions are more complex, since a buffer has to be
119 allocated to hold the output too.
120
121 The `snappy_max_compressed_length` function can be used to allocate a vector with the maximum
122 required capacity to hold the compressed output. The vector can then be passed to the
123 `snappy_compress` function as an output parameter. An output parameter is also passed to retrieve
124 the true length after compression for setting the length.
125
126 ```rust
127 # #![feature(libc)]
128 # extern crate libc;
129 # use libc::{size_t, c_int};
130 # unsafe fn snappy_compress(a: *const u8, b: size_t, c: *mut u8,
131 #                           d: *mut size_t) -> c_int { 0 }
132 # unsafe fn snappy_max_compressed_length(a: size_t) -> size_t { a }
133 # fn main() {}
134 pub fn compress(src: &[u8]) -> Vec<u8> {
135     unsafe {
136         let srclen = src.len() as size_t;
137         let psrc = src.as_ptr();
138
139         let mut dstlen = snappy_max_compressed_length(srclen);
140         let mut dst = Vec::with_capacity(dstlen as usize);
141         let pdst = dst.as_mut_ptr();
142
143         snappy_compress(psrc, srclen, pdst, &mut dstlen);
144         dst.set_len(dstlen as usize);
145         dst
146     }
147 }
148 ```
149
150 Decompression is similar, because snappy stores the uncompressed size as part of the compression
151 format and `snappy_uncompressed_length` will retrieve the exact buffer size required.
152
153 ```rust
154 # #![feature(libc)]
155 # extern crate libc;
156 # use libc::{size_t, c_int};
157 # unsafe fn snappy_uncompress(compressed: *const u8,
158 #                             compressed_length: size_t,
159 #                             uncompressed: *mut u8,
160 #                             uncompressed_length: *mut size_t) -> c_int { 0 }
161 # unsafe fn snappy_uncompressed_length(compressed: *const u8,
162 #                                      compressed_length: size_t,
163 #                                      result: *mut size_t) -> c_int { 0 }
164 # fn main() {}
165 pub fn uncompress(src: &[u8]) -> Option<Vec<u8>> {
166     unsafe {
167         let srclen = src.len() as size_t;
168         let psrc = src.as_ptr();
169
170         let mut dstlen: size_t = 0;
171         snappy_uncompressed_length(psrc, srclen, &mut dstlen);
172
173         let mut dst = Vec::with_capacity(dstlen as usize);
174         let pdst = dst.as_mut_ptr();
175
176         if snappy_uncompress(psrc, srclen, pdst, &mut dstlen) == 0 {
177             dst.set_len(dstlen as usize);
178             Some(dst)
179         } else {
180             None // SNAPPY_INVALID_INPUT
181         }
182     }
183 }
184 ```
185
186 For reference, the examples used here are also available as a [library on
187 GitHub](https://github.com/thestinger/rust-snappy).
188
189 # Destructors
190
191 Foreign libraries often hand off ownership of resources to the calling code.
192 When this occurs, we must use Rust's destructors to provide safety and guarantee
193 the release of these resources (especially in the case of panic).
194
195 For more about destructors, see the [Drop trait](../std/ops/trait.Drop.html).
196
197 # Callbacks from C code to Rust functions
198
199 Some external libraries require the usage of callbacks to report back their
200 current state or intermediate data to the caller.
201 It is possible to pass functions defined in Rust to an external library.
202 The requirement for this is that the callback function is marked as `extern`
203 with the correct calling convention to make it callable from C code.
204
205 The callback function can then be sent through a registration call
206 to the C library and afterwards be invoked from there.
207
208 A basic example is:
209
210 Rust code:
211
212 ```no_run
213 extern fn callback(a: i32) {
214     println!("I'm called from C with value {0}", a);
215 }
216
217 #[link(name = "extlib")]
218 extern {
219    fn register_callback(cb: extern fn(i32)) -> i32;
220    fn trigger_callback();
221 }
222
223 fn main() {
224     unsafe {
225         register_callback(callback);
226         trigger_callback(); // Triggers the callback
227     }
228 }
229 ```
230
231 C code:
232
233 ```c
234 typedef void (*rust_callback)(int32_t);
235 rust_callback cb;
236
237 int32_t register_callback(rust_callback callback) {
238     cb = callback;
239     return 1;
240 }
241
242 void trigger_callback() {
243   cb(7); // Will call callback(7) in Rust
244 }
245 ```
246
247 In this example Rust's `main()` will call `trigger_callback()` in C,
248 which would, in turn, call back to `callback()` in Rust.
249
250
251 ## Targeting callbacks to Rust objects
252
253 The former example showed how a global function can be called from C code.
254 However it is often desired that the callback is targeted to a special
255 Rust object. This could be the object that represents the wrapper for the
256 respective C object.
257
258 This can be achieved by passing an raw pointer to the object down to the
259 C library. The C library can then include the pointer to the Rust object in
260 the notification. This will allow the callback to unsafely access the
261 referenced Rust object.
262
263 Rust code:
264
265 ```no_run
266 #[repr(C)]
267 struct RustObject {
268     a: i32,
269     // other members
270 }
271
272 extern "C" fn callback(target: *mut RustObject, a: i32) {
273     println!("I'm called from C with value {0}", a);
274     unsafe {
275         // Update the value in RustObject with the value received from the callback
276         (*target).a = a;
277     }
278 }
279
280 #[link(name = "extlib")]
281 extern {
282    fn register_callback(target: *mut RustObject,
283                         cb: extern fn(*mut RustObject, i32)) -> i32;
284    fn trigger_callback();
285 }
286
287 fn main() {
288     // Create the object that will be referenced in the callback
289     let mut rust_object = Box::new(RustObject { a: 5 });
290
291     unsafe {
292         register_callback(&mut *rust_object, callback);
293         trigger_callback();
294     }
295 }
296 ```
297
298 C code:
299
300 ```c
301 typedef void (*rust_callback)(void*, int32_t);
302 void* cb_target;
303 rust_callback cb;
304
305 int32_t register_callback(void* callback_target, rust_callback callback) {
306     cb_target = callback_target;
307     cb = callback;
308     return 1;
309 }
310
311 void trigger_callback() {
312   cb(cb_target, 7); // Will call callback(&rustObject, 7) in Rust
313 }
314 ```
315
316 ## Asynchronous callbacks
317
318 In the previously given examples the callbacks are invoked as a direct reaction
319 to a function call to the external C library.
320 The control over the current thread is switched from Rust to C to Rust for the
321 execution of the callback, but in the end the callback is executed on the
322 same thread that called the function which triggered the callback.
323
324 Things get more complicated when the external library spawns its own threads
325 and invokes callbacks from there.
326 In these cases access to Rust data structures inside the callbacks is
327 especially unsafe and proper synchronization mechanisms must be used.
328 Besides classical synchronization mechanisms like mutexes, one possibility in
329 Rust is to use channels (in `std::sync::mpsc`) to forward data from the C
330 thread that invoked the callback into a Rust thread.
331
332 If an asynchronous callback targets a special object in the Rust address space
333 it is also absolutely necessary that no more callbacks are performed by the
334 C library after the respective Rust object gets destroyed.
335 This can be achieved by unregistering the callback in the object's
336 destructor and designing the library in a way that guarantees that no
337 callback will be performed after deregistration.
338
339 # Linking
340
341 The `link` attribute on `extern` blocks provides the basic building block for
342 instructing rustc how it will link to native libraries. There are two accepted
343 forms of the link attribute today:
344
345 * `#[link(name = "foo")]`
346 * `#[link(name = "foo", kind = "bar")]`
347
348 In both of these cases, `foo` is the name of the native library that we're
349 linking to, and in the second case `bar` is the type of native library that the
350 compiler is linking to. There are currently three known types of native
351 libraries:
352
353 * Dynamic - `#[link(name = "readline")]`
354 * Static - `#[link(name = "my_build_dependency", kind = "static")]`
355 * Frameworks - `#[link(name = "CoreFoundation", kind = "framework")]`
356
357 Note that frameworks are only available on OSX targets.
358
359 The different `kind` values are meant to differentiate how the native library
360 participates in linkage. From a linkage perspective, the Rust compiler creates
361 two flavors of artifacts: partial (rlib/staticlib) and final (dylib/binary).
362 Native dynamic library and framework dependencies are propagated to the final
363 artifact boundary, while static library dependencies are not propagated at
364 all, because the static libraries are integrated directly into the subsequent
365 artifact.
366
367 A few examples of how this model can be used are:
368
369 * A native build dependency. Sometimes some C/C++ glue is needed when writing
370   some Rust code, but distribution of the C/C++ code in a library format is
371   a burden. In this case, the code will be archived into `libfoo.a` and then the
372   Rust crate would declare a dependency via `#[link(name = "foo", kind =
373   "static")]`.
374
375   Regardless of the flavor of output for the crate, the native static library
376   will be included in the output, meaning that distribution of the native static
377   library is not necessary.
378
379 * A normal dynamic dependency. Common system libraries (like `readline`) are
380   available on a large number of systems, and often a static copy of these
381   libraries cannot be found. When this dependency is included in a Rust crate,
382   partial targets (like rlibs) will not link to the library, but when the rlib
383   is included in a final target (like a binary), the native library will be
384   linked in.
385
386 On OSX, frameworks behave with the same semantics as a dynamic library.
387
388 # Unsafe blocks
389
390 Some operations, like dereferencing raw pointers or calling functions that have been marked
391 unsafe are only allowed inside unsafe blocks. Unsafe blocks isolate unsafety and are a promise to
392 the compiler that the unsafety does not leak out of the block.
393
394 Unsafe functions, on the other hand, advertise it to the world. An unsafe function is written like
395 this:
396
397 ```rust
398 unsafe fn kaboom(ptr: *const i32) -> i32 { *ptr }
399 ```
400
401 This function can only be called from an `unsafe` block or another `unsafe` function.
402
403 # Accessing foreign globals
404
405 Foreign APIs often export a global variable which could do something like track
406 global state. In order to access these variables, you declare them in `extern`
407 blocks with the `static` keyword:
408
409 ```no_run
410 # #![feature(libc)]
411 extern crate libc;
412
413 #[link(name = "readline")]
414 extern {
415     static rl_readline_version: libc::c_int;
416 }
417
418 fn main() {
419     println!("You have readline version {} installed.",
420              rl_readline_version as i32);
421 }
422 ```
423
424 Alternatively, you may need to alter global state provided by a foreign
425 interface. To do this, statics can be declared with `mut` so we can mutate
426 them.
427
428 ```no_run
429 # #![feature(libc)]
430 extern crate libc;
431
432 use std::ffi::CString;
433 use std::ptr;
434
435 #[link(name = "readline")]
436 extern {
437     static mut rl_prompt: *const libc::c_char;
438 }
439
440 fn main() {
441     let prompt = CString::new("[my-awesome-shell] $").unwrap();
442     unsafe {
443         rl_prompt = prompt.as_ptr();
444
445         println!("{:?}", rl_prompt);
446
447         rl_prompt = ptr::null();
448     }
449 }
450 ```
451
452 Note that all interaction with a `static mut` is unsafe, both reading and
453 writing. Dealing with global mutable state requires a great deal of care.
454
455 # Foreign calling conventions
456
457 Most foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when
458 calling foreign functions. Some foreign functions, most notably the Windows API, use other calling
459 conventions. Rust provides a way to tell the compiler which convention to use:
460
461 ```rust
462 # #![feature(libc)]
463 extern crate libc;
464
465 #[cfg(all(target_os = "win32", target_arch = "x86"))]
466 #[link(name = "kernel32")]
467 #[allow(non_snake_case)]
468 extern "stdcall" {
469     fn SetEnvironmentVariableA(n: *const u8, v: *const u8) -> libc::c_int;
470 }
471 # fn main() { }
472 ```
473
474 This applies to the entire `extern` block. The list of supported ABI constraints
475 are:
476
477 * `stdcall`
478 * `aapcs`
479 * `cdecl`
480 * `fastcall`
481 * `vectorcall`
482 This is currently hidden behind the `abi_vectorcall` gate and is subject to change.
483 * `Rust`
484 * `rust-intrinsic`
485 * `system`
486 * `C`
487 * `win64`
488
489 Most of the abis in this list are self-explanatory, but the `system` abi may
490 seem a little odd. This constraint selects whatever the appropriate ABI is for
491 interoperating with the target's libraries. For example, on win32 with a x86
492 architecture, this means that the abi used would be `stdcall`. On x86_64,
493 however, windows uses the `C` calling convention, so `C` would be used. This
494 means that in our previous example, we could have used `extern "system" { ... }`
495 to define a block for all windows systems, not only x86 ones.
496
497 # Interoperability with foreign code
498
499 Rust guarantees that the layout of a `struct` is compatible with the platform's
500 representation in C only if the `#[repr(C)]` attribute is applied to it.
501 `#[repr(C, packed)]` can be used to lay out struct members without padding.
502 `#[repr(C)]` can also be applied to an enum.
503
504 Rust's owned boxes (`Box<T>`) use non-nullable pointers as handles which point
505 to the contained object. However, they should not be manually created because
506 they are managed by internal allocators. References can safely be assumed to be
507 non-nullable pointers directly to the type.  However, breaking the borrow
508 checking or mutability rules is not guaranteed to be safe, so prefer using raw
509 pointers (`*`) if that's needed because the compiler can't make as many
510 assumptions about them.
511
512 Vectors and strings share the same basic memory layout, and utilities are
513 available in the `vec` and `str` modules for working with C APIs. However,
514 strings are not terminated with `\0`. If you need a NUL-terminated string for
515 interoperability with C, you should use the `CString` type in the `std::ffi`
516 module.
517
518 The [`libc` crate on crates.io][libc] includes type aliases and function
519 definitions for the C standard library in the `libc` module, and Rust links
520 against `libc` and `libm` by default.
521
522 # The "nullable pointer optimization"
523
524 Certain types are defined to not be `null`. This includes references (`&T`,
525 `&mut T`), boxes (`Box<T>`), and function pointers (`extern "abi" fn()`).
526 When interfacing with C, pointers that might be null are often used.
527 As a special case, a generic `enum` that contains exactly two variants, one of
528 which contains no data and the other containing a single field, is eligible
529 for the "nullable pointer optimization". When such an enum is instantiated
530 with one of the non-nullable types, it is represented as a single pointer,
531 and the non-data variant is represented as the null pointer. So
532 `Option<extern "C" fn(c_int) -> c_int>` is how one represents a nullable
533 function pointer using the C ABI.
534
535 # Calling Rust code from C
536
537 You may wish to compile Rust code in a way so that it can be called from C. This is
538 fairly easy, but requires a few things:
539
540 ```rust
541 #[no_mangle]
542 pub extern fn hello_rust() -> *const u8 {
543     "Hello, world!\0".as_ptr()
544 }
545 # fn main() {}
546 ```
547
548 The `extern` makes this function adhere to the C calling convention, as
549 discussed above in "[Foreign Calling
550 Conventions](ffi.html#foreign-calling-conventions)". The `no_mangle`
551 attribute turns off Rust's name mangling, so that it is easier to link to.
552
553 # FFI and panics
554
555 It’s important to be mindful of `panic!`s when working with FFI. A `panic!`
556 across an FFI boundary is undefined behavior. If you’re writing code that may
557 panic, you should run it in another thread, so that the panic doesn’t bubble up
558 to C:
559
560 ```rust
561 use std::thread;
562
563 #[no_mangle]
564 pub extern fn oh_no() -> i32 {
565     let h = thread::spawn(|| {
566         panic!("Oops!");
567     });
568
569     match h.join() {
570         Ok(_) => 1,
571         Err(_) => 0,
572     }
573 }
574 # fn main() {}
575 ```
576
577 # Representing opaque structs
578
579 Sometimes, a C library wants to provide a pointer to something, but not let you
580 know the internal details of the thing it wants. The simplest way is to use a
581 `void *` argument:
582
583 ```c
584 void foo(void *arg);
585 void bar(void *arg);
586 ```
587
588 We can represent this in Rust with the `c_void` type:
589
590 ```rust
591 # #![feature(libc)]
592 extern crate libc;
593
594 extern "C" {
595     pub fn foo(arg: *mut libc::c_void);
596     pub fn bar(arg: *mut libc::c_void);
597 }
598 # fn main() {}
599 ```
600
601 This is a perfectly valid way of handling the situation. However, we can do a bit
602 better. To solve this, some C libraries will instead create a `struct`, where
603 the details and memory layout of the struct are private. This gives some amount
604 of type safety. These structures are called ‘opaque’. Here’s an example, in C:
605
606 ```c
607 struct Foo; /* Foo is a structure, but its contents are not part of the public interface */
608 struct Bar;
609 void foo(struct Foo *arg);
610 void bar(struct Bar *arg);
611 ```
612
613 To do this in Rust, let’s create our own opaque types with `enum`:
614
615 ```rust
616 pub enum Foo {}
617 pub enum Bar {}
618
619 extern "C" {
620     pub fn foo(arg: *mut Foo);
621     pub fn bar(arg: *mut Bar);
622 }
623 # fn main() {}
624 ```
625
626 By using an `enum` with no variants, we create an opaque type that we can’t
627 instantiate, as it has no variants. But because our `Foo` and `Bar` types are
628 different, we’ll get type safety between the two of them, so we cannot
629 accidentally pass a pointer to `Foo` to `bar()`.