【问题标题】:How do I create static C strings?如何创建静态 C 字符串?
【发布时间】:2015-06-16 07:28:31
【问题描述】:

我想在 Rust 中创建一个插件模块(共享库),它导出包含静态 C 字符串的 C 兼容结构。 2014 年 9 月,this Stack Overflow question 确定这是不可能的。截至 2015 年 1 月,根据this Reddit thread,这仍然是不可能的。自那以后有什么变化吗?

【问题讨论】:

  • 我希望 RFC 911 能对此有所帮助 - 它允许在静态上下文中调用 as_ptr

标签: string static rust ffi


【解决方案1】:

以下似乎可以解决问题。我真的不希望结构是可变的,但是如果我不将它标记为 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\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));
    }
}

输出(在 64 位 linux 上)是 ...

a constant c string
another constant c string
Mystruct size 16

【讨论】:

    猜你喜欢
    • 2014-11-10
    • 2015-02-12
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多