Copying string into buffer


#1

I’m trying to figure out how to deal with ffi (attempting to use rust library in python).

Having some String, my rust function will receive pointer (*char), and should
fill it wi the copy of the string. So far I’ve got something like this:

#[no_mangle]
pub extern fn foo(buf: *mut [u8; MAX_LEN]) -> u32 {
    let s:String = "abc";
    let mut _buf = unsafe { *buf };
    _buf.clone_from_slice(s.into_bytes().as_slice());
    return 1

}

but rust complain that "error: use of unstable library feature ‘convert’: waiting on RFC revision"
at the call to .as_slice(). What’s the best way to do it?


#2

Use &is.into_bytes(). Slicing syntax rather than the .as_slice() method.

You may need &(s.into_bytes())[…]


#3

The *buf means that the write happens to a local copy on the stack, and the pointer you receive isn’t modified at all.

You may want:

#![feature(collections)]

#[no_mangle]
pub extern fn foo(buf: *mut [u8; 10]) -> u32 {
    let s = "abc";
    unsafe {
        (*buf).clone_from_slice(s.as_bytes());
    }
    1
}

However, this still requires an unstable feature, and so either requires a nightly compiler, or rewriting, e.g.

#[no_mangle]
pub extern fn foo(buf: *mut [u8; 10]) -> u32 {
    let s = "abc";
    unsafe {
        for (place, b) in (*buf).iter_mut().zip(s.bytes()) {
            *place = b;
        }
    }
    1
}

#4

That was it, thanks.(also it would be nice to have this example in the book)