我對Rust很新。我如何從可以在Python中使用的Rust函數返回String
?從Rust函數返回一個字符串到Python
這裏是我的防鏽實現:
use std::ffi::CString;
#[no_mangle]
pub extern fn query() -> CString {
let s = CString::new("Hello!").unwrap();
return s;
}
並調用它的Python代碼:
from ctypes import cdll, c_char_p
lib = cdll.LoadLibrary("target/release/libtest.so")
result = lib.query()
print(c_char_p(result).value)
我得到一個分段錯誤時,它的運行。
編輯:使用弗拉基米爾Matveev的鏽代碼下面我能夠得到它與修改了自己的Python代碼工作:
from ctypes import *
lib = cdll.LoadLibrary("target/release/libtest.so")
lib.query.restype = c_char_p
result = lib.query()
print cast(result, c_char_p).value
lib.free_query(result)
請檢閱http:// stackoverflow。com/questions/30440068/segmentation-fault-when-calling-a-rust-lib-with-ruby-ffi and http://stackoverflow.com/questions/30312885/pass-python-list-to-embedded-rust-功能/ 30313295#30313295並讓我們知道您的問題如何不同。 – Shepmaster
我已經回顧了這兩個問題,他們確實有所不同。在第一個中,調用來自Ruby,我的問題來自Python。 在第二個問題中,返回值是一個整數,這是一個簡單的例子。這裏,返回值具體是一個字符串值。 – LeeMobile
生鏽的一面絕對沒有什麼不同,它應該根據你所說的語言而改變。就Rust代碼而言,C正在調用它。其他任何語言都在調用看起來像C代碼的東西。 – Shepmaster