Returning a String from Rust function to Python

后端 未结 2 1526
别跟我提以往
别跟我提以往 2021-01-01 15:31

I\'m very new to Rust. How would I return a String from a Rust function that can be used in Python?

Here is my Rust implementation:

use          


        
2条回答
  •  既然无缘
    2021-01-01 16:00

    The problem here is that you are returning a CString directly, which does not correspond to the representation of a string in C (you can see here the source code of CString).

    You should be returning a pointer to the string, by using s.as_ptr(). However, you need to make sure that the string is not deallocated at the end of the function, since that would result in a dangling pointer.

    The only solution I can think of is to use forget to let rust forget the variable instead of freeing it. Of course you will need to find a way to free the string later to avoid a memory leak (see Vladimir's answer).

    With the changes I mentioned, your Rust code should be the following:

    use std::ffi::CString;
    use std::mem;
    
    #[no_mangle]
    pub extern fn query() -> *const i8 {
        let s = CString::new("Hello!").unwrap();
        let ptr = s.as_ptr();
        mem::forget(s);
        return ptr;
    }
    

提交回复
热议问题