如何创建静态C字符串? [英] How do I create static C strings?

查看:174
本文介绍了如何创建静态C字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Rust中创建一个插件模块(共享库),以导出包含静态C字符串的C兼容结构. 2014年9月,此堆栈溢出问题判定不可能.截至2015年1月,根据此Reddit线程.从那以后有什么改变吗?

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?

推荐答案

以下似乎可以解决问题.我真的不希望该结构是可变的,但是如果我不将其标记为mut,则会出现core :: marker :: Sync错误.

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));
    }
}

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

The output (on 64 bit linux) is ...

a constant c string
another constant c string
Mystruct size 16

这篇关于如何创建静态C字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆