Creating a static C struct containing strings

前端 未结 2 1965
旧时难觅i
旧时难觅i 2020-12-11 16:45

I\'m trying to create a dynamic library in Rust that exports a struct as a symbol that will be loaded into a C program via dlopen().

However, I\'m was running into s

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 17:17

    The short answer is that you can't statically allocate such a struct. Future Rust will probably gain this ability.

    What you can do, is statically allocate a struct that contains null pointers, and set those null pointers to something useful when you call the function. Rust has static mut. It requires unsafe code, is not threadsafe at all and is (to the best of my knowledge) considered a code smell.

    Right here I consider it a workaround to the fact that there is no way to turn a &[T] into a *const T in a static.

    static S: &'static [u8] = b"http://example.org/eg-amp_rust\n\0";
    static mut desc: LV2Descriptor = LV2Descriptor {
        amp_uri: 0 as *const libc::c_char, // ptr::null() isn't const fn (yet)
    };
    
    #[no_mangle]
    pub extern fn lv2_descriptor(index: i32) -> *const LV2Descriptor {
         let ptr = S.as_ptr() as *const libc::c_char;
         unsafe {
            desc.amp_uri = ptr;
            &desc as *const LV2Descriptor
         }
    }
    

    answer copied from duplicate question

提交回复
热议问题