Exposing POD constants to C


#1

I have bunch of &'static constants like this:

/// The windows-1252 encoding.
pub const WINDOWS_1252: &'static Encoding = &Encoding {
    name: "windows-1252",
    variant: VariantEncoding::SingleByte(data::WINDOWS_1252_DATA),
};

I’d like to expose these as static WINDOWS_1252_ENCODING: *const Encoding to C such that the storage of the pointers is static in Rust and C sees them through external linkage.

The Book talks about accessing globals whose storage is allocated in C code but doesn’t say how to expose globals from Rust to C. The syntax doesn’t work in the obvious way by just adding = and an initializer.

Is it impossible to expose some POD constants from Rust to C so that C sees them as variables with external linkage? Do I have to create a trivial function for getting each pointer instead?


#2

Have you tried #[no_mangle] pub static WINDOWS_1252 ...?


name: "windows-1252",

Remember that string literals in Rust aren’t nul-terminated.


#3

Indeed that works. It has so much less ceremony than C-linkage functions that it didn’t occur to me to try it.

So this works:

Rust:

#[no_mangle]
pub static UTF8_ENCODING: *const Encoding = UTF_8;

C:

extern const Encoding* UTF8_ENCODING;

#4

The C-side declaration should be:

extern const Encoding* const UTF8_ENCODING;

(const on both sides of *.)