Skip to content

Commit 433ea0b

Browse files
committed
Add C -> Rust example to FFI chapter of the book.
Fixes #10489.
1 parent d1ab379 commit 433ea0b

File tree

1 file changed

+46
-28
lines changed

1 file changed

+46
-28
lines changed

src/doc/trpl/ffi.md

+46-28
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ snappy includes a C interface (documented in
1111
The following is a minimal example of calling a foreign function which will
1212
compile if snappy is installed:
1313

14-
~~~~no_run
14+
```no_run
1515
extern crate libc;
1616
use libc::size_t;
1717
@@ -24,7 +24,7 @@ fn main() {
2424
let x = unsafe { snappy_max_compressed_length(100) };
2525
println!("max compressed length of a 100 byte buffer: {}", x);
2626
}
27-
~~~~
27+
```
2828

2929
The `extern` block is a list of function signatures in a foreign library, in
3030
this case with the platform's C ABI. The `#[link(...)]` attribute is used to
@@ -44,7 +44,7 @@ keeping the binding correct at runtime.
4444

4545
The `extern` block can be extended to cover the entire snappy API:
4646

47-
~~~~no_run
47+
```no_run
4848
extern crate libc;
4949
use libc::{c_int, size_t};
5050
@@ -66,7 +66,7 @@ extern {
6666
compressed_length: size_t) -> c_int;
6767
}
6868
# fn main() {}
69-
~~~~
69+
```
7070

7171
# Creating a safe interface
7272

@@ -79,7 +79,7 @@ vectors as pointers to memory. Rust's vectors are guaranteed to be a contiguous
7979
length is number of elements currently contained, and the capacity is the total size in elements of
8080
the allocated memory. The length is less than or equal to the capacity.
8181

82-
~~~~
82+
```
8383
# extern crate libc;
8484
# use libc::{c_int, size_t};
8585
# unsafe fn snappy_validate_compressed_buffer(_: *const u8, _: size_t) -> c_int { 0 }
@@ -89,7 +89,7 @@ pub fn validate_compressed_buffer(src: &[u8]) -> bool {
8989
snappy_validate_compressed_buffer(src.as_ptr(), src.len() as size_t) == 0
9090
}
9191
}
92-
~~~~
92+
```
9393

9494
The `validate_compressed_buffer` wrapper above makes use of an `unsafe` block, but it makes the
9595
guarantee that calling it is safe for all inputs by leaving off `unsafe` from the function
@@ -103,7 +103,7 @@ required capacity to hold the compressed output. The vector can then be passed t
103103
`snappy_compress` function as an output parameter. An output parameter is also passed to retrieve
104104
the true length after compression for setting the length.
105105

106-
~~~~
106+
```
107107
# extern crate libc;
108108
# use libc::{size_t, c_int};
109109
# unsafe fn snappy_compress(a: *const u8, b: size_t, c: *mut u8,
@@ -124,12 +124,12 @@ pub fn compress(src: &[u8]) -> Vec<u8> {
124124
dst
125125
}
126126
}
127-
~~~~
127+
```
128128

129129
Decompression is similar, because snappy stores the uncompressed size as part of the compression
130130
format and `snappy_uncompressed_length` will retrieve the exact buffer size required.
131131

132-
~~~~
132+
```
133133
# extern crate libc;
134134
# use libc::{size_t, c_int};
135135
# unsafe fn snappy_uncompress(compressed: *const u8,
@@ -159,7 +159,7 @@ pub fn uncompress(src: &[u8]) -> Option<Vec<u8>> {
159159
}
160160
}
161161
}
162-
~~~~
162+
```
163163

164164
For reference, the examples used here are also available as an [library on
165165
GitHub](https://github.com/thestinger/rust-snappy).
@@ -185,7 +185,7 @@ A basic example is:
185185

186186
Rust code:
187187

188-
~~~~no_run
188+
```no_run
189189
extern fn callback(a: i32) {
190190
println!("I'm called from C with value {0}", a);
191191
}
@@ -202,11 +202,11 @@ fn main() {
202202
trigger_callback(); // Triggers the callback
203203
}
204204
}
205-
~~~~
205+
```
206206

207207
C code:
208208

209-
~~~~c
209+
```c
210210
typedef void (*rust_callback)(int32_t);
211211
rust_callback cb;
212212

@@ -218,7 +218,7 @@ int32_t register_callback(rust_callback callback) {
218218
void trigger_callback() {
219219
cb(7); // Will call callback(7) in Rust
220220
}
221-
~~~~
221+
```
222222
223223
In this example Rust's `main()` will call `trigger_callback()` in C,
224224
which would, in turn, call back to `callback()` in Rust.
@@ -238,7 +238,7 @@ referenced Rust object.
238238
239239
Rust code:
240240
241-
~~~~no_run
241+
```no_run
242242
#[repr(C)]
243243
struct RustObject {
244244
a: i32,
@@ -269,11 +269,11 @@ fn main() {
269269
trigger_callback();
270270
}
271271
}
272-
~~~~
272+
```
273273

274274
C code:
275275

276-
~~~~c
276+
```c
277277
typedef void (*rust_callback)(void*, int32_t);
278278
void* cb_target;
279279
rust_callback cb;
@@ -287,7 +287,7 @@ int32_t register_callback(void* callback_target, rust_callback callback) {
287287
void trigger_callback() {
288288
cb(cb_target, 7); // Will call callback(&rustObject, 7) in Rust
289289
}
290-
~~~~
290+
```
291291
292292
## Asynchronous callbacks
293293
@@ -366,13 +366,13 @@ the `link_args` attribute. This attribute is applied to `extern` blocks and
366366
specifies raw flags which need to get passed to the linker when producing an
367367
artifact. An example usage would be:
368368
369-
~~~ no_run
369+
``` no_run
370370
#![feature(link_args)]
371371
372372
#[link_args = "-foo -bar -baz"]
373373
extern {}
374374
# fn main() {}
375-
~~~
375+
```
376376

377377
Note that this feature is currently hidden behind the `feature(link_args)` gate
378378
because this is not a sanctioned way of performing linking. Right now rustc
@@ -393,9 +393,9 @@ the compiler that the unsafety does not leak out of the block.
393393
Unsafe functions, on the other hand, advertise it to the world. An unsafe function is written like
394394
this:
395395

396-
~~~~
396+
```
397397
unsafe fn kaboom(ptr: *const int) -> int { *ptr }
398-
~~~~
398+
```
399399

400400
This function can only be called from an `unsafe` block or another `unsafe` function.
401401

@@ -405,7 +405,7 @@ Foreign APIs often export a global variable which could do something like track
405405
global state. In order to access these variables, you declare them in `extern`
406406
blocks with the `static` keyword:
407407

408-
~~~no_run
408+
```no_run
409409
extern crate libc;
410410
411411
#[link(name = "readline")]
@@ -417,13 +417,13 @@ fn main() {
417417
println!("You have readline version {} installed.",
418418
rl_readline_version as int);
419419
}
420-
~~~
420+
```
421421

422422
Alternatively, you may need to alter global state provided by a foreign
423423
interface. To do this, statics can be declared with `mut` so rust can mutate
424424
them.
425425

426-
~~~no_run
426+
```no_run
427427
extern crate libc;
428428
429429
use std::ffi::CString;
@@ -440,15 +440,15 @@ fn main() {
440440
// get a line, process it
441441
unsafe { rl_prompt = ptr::null(); }
442442
}
443-
~~~
443+
```
444444

445445
# Foreign calling conventions
446446

447447
Most foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when
448448
calling foreign functions. Some foreign functions, most notably the Windows API, use other calling
449449
conventions. Rust provides a way to tell the compiler which convention to use:
450450

451-
~~~~
451+
```
452452
extern crate libc;
453453
454454
#[cfg(all(target_os = "win32", target_arch = "x86"))]
@@ -458,7 +458,7 @@ extern "stdcall" {
458458
fn SetEnvironmentVariableA(n: *const u8, v: *const u8) -> libc::c_int;
459459
}
460460
# fn main() { }
461-
~~~~
461+
```
462462

463463
This applies to the entire `extern` block. The list of supported ABI constraints
464464
are:
@@ -518,3 +518,21 @@ with one of the non-nullable types, it is represented as a single pointer,
518518
and the non-data variant is represented as the null pointer. So
519519
`Option<extern "C" fn(c_int) -> c_int>` is how one represents a nullable
520520
function pointer using the C ABI.
521+
522+
# Calling Rust code from C
523+
524+
You may wish to compile Rust code in a way so that it can be called from C. This is
525+
fairly easy, but requires a few things:
526+
527+
```
528+
#[no_mangle]
529+
pub extern fn hello_rust() -> *const u8 {
530+
"Hello, world!\0".as_ptr()
531+
}
532+
```
533+
534+
The `extern` makes this function adhere to the C calling convention, as
535+
discussed above in "[Foreign Calling
536+
Conventions](guide-ffi.html#foreign-calling-conventions)". The `no_mangle`
537+
attribute turns off Rust's name mangling, so that it is easier to link to.
538+

0 commit comments

Comments
 (0)