如何创建静态 C 字符串?
How do I create static C strings?
我想在 Rust 中创建一个插件模块(共享库),它导出一个包含静态 C 字符串的 C 兼容结构。 2014 年 9 月,this Stack Overflow question determined it wasn't possible. As of Jan 2015 this still was not possible as per this Reddit thread。自那以后有什么变化吗?
以下似乎可以解决问题。我真的不希望该结构可变,但如果我不将其标记为 mut,我会收到 core::marker::Sync 错误。
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[=10=]" as *const u8;
#[no_mangle]
pub static mut mystaticstruct: Mystruct = Mystruct {
s1: CONST_C_STR,
s2: b"another constant c string[=10=]" 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));
}
}
输出(64 位linux)是...
a constant c string
another constant c string
Mystruct size 16
我想在 Rust 中创建一个插件模块(共享库),它导出一个包含静态 C 字符串的 C 兼容结构。 2014 年 9 月,this Stack Overflow question determined it wasn't possible. As of Jan 2015 this still was not possible as per this Reddit thread。自那以后有什么变化吗?
以下似乎可以解决问题。我真的不希望该结构可变,但如果我不将其标记为 mut,我会收到 core::marker::Sync 错误。
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[=10=]" as *const u8;
#[no_mangle]
pub static mut mystaticstruct: Mystruct = Mystruct {
s1: CONST_C_STR,
s2: b"another constant c string[=10=]" 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));
}
}
输出(64 位linux)是...
a constant c string
another constant c string
Mystruct size 16