简体   繁体   中英

How can I access a C global variable/constant in Rust FFI?

I need to access a value of a constant exported from C in Rust.

I want to read the value from the actual symbol, and not just copy'n'paste the value to Rust (in my case the value is a pointer, and C checks for pointer equality).

extern void *magic;

What's the syntax to get magic: *const c_void readable in Rust?

use std::os::raw::c_void;

extern "C" {
    #[no_mangle]
    static magic: *const c_void;
}

Optionally, before the extern there can be #[link(kind="static", name="<c library name>")] to get the symbol actually linked.

Externally linkable items, even if constant, need be declared with static , not just const keyword (otherwise you get "extern items cannot be const ").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM