How do I create static C strings?

给你一囗甜甜゛ 提交于 2019-12-11 10:35:38

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/29563785/how-do-i-create-static-c-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!