将包含从Rust到C的字符串数组的C符号公开

时间:2016-03-19 18:36:33

标签: rust ffi

我有以下C代码:

const char * const Vmod_Spec[] = {
    "example.hello\0Vmod_Func_example.hello\0STRING\0STRING\0",
    "INIT\0Vmod_Func_example._init",
    0
};

从此代码编译.so后,我可以使用dlsym加载此符号并获取Vmod_Spec的内容并对其进行迭代。如何从Rust中获得与此类符号相同的结果?

1 个答案:

答案 0 :(得分:1)

Rust的等价物是将[*const c_char;3]作为static值公开。问题是,如果您声明这样的值,您将收到错误:error: the trait core::marker::Sync is not implemented for the type *const i8 [E0277]。并且您无法为*const c_char实施此特征,因为您不拥有此类型。解决方法是在*const c_char周围声明一个包装类型并改为使用它:

struct Wrapper(*const c_char)
unsafe impl Sync for Wrapper { }
#[no_mangle]
pub static Vmod_Spec: [Wrapper; 3] = etc..

然后我会有一个Vmod_Spec符号,指向一组数值。