Skip to content

Commit 1b10391

Browse files
alexcrichtonemberian
authored andcommitted
Add some documentation about globals in ffi docs
1 parent 403c52d commit 1b10391

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

doc/tutorial-ffi.md

+42
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,48 @@ unsafe fn kaboom(ptr: *int) -> int { *ptr }
228228

229229
This function can only be called from an `unsafe` block or another `unsafe` function.
230230

231+
# Accessing foreign globals
232+
233+
Foreign APIs often export a global variable which could do something like track
234+
global state. In order to access these variables, you declare them in `extern`
235+
blocks with the `static` keyword:
236+
237+
~~~{.xfail-test}
238+
use std::libc;
239+
240+
#[link_args = "-lreadline"]
241+
extern {
242+
static rl_readline_version: libc::c_int;
243+
}
244+
245+
fn main() {
246+
println(fmt!("You have readline version %d installed.",
247+
rl_readline_version as int));
248+
}
249+
~~~
250+
251+
Alternatively, you may need to alter global state provided by a foreign
252+
interface. To do this, statics can be declared with `mut` so rust can mutate
253+
them.
254+
255+
~~~{.xfail-test}
256+
use std::libc;
257+
use std::ptr;
258+
259+
#[link_args = "-lreadline"]
260+
extern {
261+
static mut rl_prompt: *libc::c_char;
262+
}
263+
264+
fn main() {
265+
do "[my-awesome-shell] $".as_c_str |buf| {
266+
unsafe { rl_prompt = buf; }
267+
// get a line, process it
268+
unsafe { rl_prompt = ptr::null(); }
269+
}
270+
}
271+
~~~
272+
231273
# Foreign calling conventions
232274

233275
Most foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when

0 commit comments

Comments
 (0)