lua使用rust代码(第四期)--传入string
lua给rust传入string,过程与之前的c_int
相同。都是需要先转成c类型(const char *) 再转成rust类型(Cstr)。中间稍有错误调用就会报错 段错误(核心已转储) 本文将基于上一期示例lua使用rust代码(第三期)--Vec<struct>
lib.rs
fn get_info_with_url(c_url:*const c_char,) -> Result<Vec<HostInfo>, reqwest::Error>{
//get data through api by reqwest
let url_r = unsafe { CStr::from_ptr(c_url) };
let buf: &[u8] = url_r.to_bytes();
let url: &str = std::str::from_utf8(buf).unwrap();
let res: Vec<HostInfo> = reqwest::Client::new()
.get(url)
.send()?
.json()?;
Ok(res)
}
libexample.lua
ffi = require("ffi")
ffi.cdef[[
typedef struct {
char * ip;
int ip_len;
int port;
} hostinfo_t;
hostinfo_t * get_all_data_with_url(char*,int*);
]]
function get_cstr(text)
local c_str = ffi.new("char[?]", #text)
ffi.copy(c_str, text)
return c_str
end
function parse_info(data)
local info = {}
info["ip"] = ffi.string(data.ip,data.ip_len)
info["port"] = data.port
return info
end
example_api = {}
example_api.url=get_cstr("http://example.com/api/host/")
function example_api.set_url(url)
example_api.url=get_cstr(url)
end
function example_api.get_data()
local intPtr = ffi.typeof("int[1]")
local len = intPtr()
local data = rust_lib.get_all_data_with_url(example_api.url,len)
local res={}
for i=0,len[0]-1 do
res[i] = parse_info(data[i])
end
test.lua
local rust_lib = require("libexample")
rust_lib.set_url("http://example.com/api/v2/host/")
local res = rust_lib.get_data()