These are chat archives for rust-lang/rust

10th
Sep 2015
Pete Hayes
@petehayes102
Sep 10 2015 15:26
Would anyone be able to help me with this: https://gist.github.com/petehayes102/e04d03a20e57a22dca7c
I'm trying to pass a var by reference from C, then bind a new value in Rust
I'm not sure my approach is even valid?? I can't find anything helpful in articles related to passing by reference between languages
Erik Hedvall
@Ogeon
Sep 10 2015 15:32

You need to make var itself mutable:

pub extern "C" fn test(mut var: *mut c_char) { //note the extra `mut` keyword
    var = CString::new("newvar").unwrap().as_ptr() as *mut c_char;
}

Don't forget to make sure that the string isn't destroyed at the end of test.

Pete Hayes
@petehayes102
Sep 10 2015 15:35
Ok, I assume that'd be a manual job with raw pointers?
i.e. if I don't touch it, everything stays working? :)
Peter Atashian
@retep998
Sep 10 2015 15:43
var = CString::new("newvar").unwrap().as_ptr() as *mut c_char;
This is so totally wrong, because right after that statement that CString will get destroyed and the pointer invalid.
Pete Hayes
@petehayes102
Sep 10 2015 15:44
Heh, no worries. I did caveat that my approach is probably really stupid
I really don’t know my way around Rust. Would you be able to point me in the right direction?
Peter Atashian
@retep998
Sep 10 2015 15:46
That Rust function won't modify the pointer you're passing in. You'd have to pass a pointer to the pointer and mutate that.
Also, if you want to transfer ownership of a C style string to C, you want to use CString.into_raw() which consumes the CString and gives you a *mut c_char which will last as long as you want until you CString::from_raw that pointer later on when you return it to the Rust world.
Pete Hayes
@petehayes102
Sep 10 2015 15:48
Ok, thanks mate.
Peter Atashian
@retep998
Sep 10 2015 15:48
Do note that Rust and C do not necessarily use the same allocator, so make sure that C is responsible for freeing any strings allocated by C, and that Rust is responsible for freeing any strings allocated by Rust
Pete Hayes
@petehayes102
Sep 10 2015 15:49
I can’t see into_raw() in the docs
Is it a new fn?
Peter Atashian
@retep998
Sep 10 2015 15:49
Oh, it was added in Rust 1.4 nightly
Pete Hayes
@petehayes102
Sep 10 2015 15:49
Ah
Found it. Thanks for your help mate!