Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 689
Kornel Avatar asked Dec 10 '22 10:12

Kornel


1 Answers

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").

like image 62
Kornel Avatar answered Jan 06 '23 07:01

Kornel