Commit 1b10391 1 parent 403c52d commit 1b10391 Copy full SHA for 1b10391
File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -228,6 +228,48 @@ unsafe fn kaboom(ptr: *int) -> int { *ptr }
228
228
229
229
This function can only be called from an ` unsafe ` block or another ` unsafe ` function.
230
230
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
+
231
273
# Foreign calling conventions
232
274
233
275
Most foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when
You can’t perform that action at this time.
0 commit comments