I want to create a plugin module (shared lib) in Rust that exports a C compatible structure containing static C strings. In Sept 2014, this Stack Overflow question determined it wasn't possible. As of Jan 2015 this still was not possible as per this Reddit thread. Has anything changed since?
The following seems to do the trick. I don't really want the struct to be mutable, but I get core::marker::Sync errors if I don't mark it as mut.
extern crate libc;
use libc::funcs::c95::stdio::puts;
use std::mem;
pub struct Mystruct {
s1: *const u8,
s2: *const u8,
}
const CONST_C_STR: *const u8 = b"a constant c string\0" as *const u8;
#[no_mangle]
pub static mut mystaticstruct: Mystruct = Mystruct {
s1: CONST_C_STR,
s2: b"another constant c string\0" as *const u8
};
fn main() {
unsafe{
puts(mystaticstruct.s1 as *const i8); // puts likes i8
puts(mystaticstruct.s2 as *const i8);
println!("Mystruct size {}", mem::size_of_val(&mystaticstruct));
}
}
The output (on 64 bit linux) is ...
a constant c string
another constant c string
Mystruct size 16