lua使用rust代码(第四期)--传入string

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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值