lua使用rust代码(第三期)--Vec<struct>

lua使用rust代码(第三期)--Vec<struct>

[toc]

前言

在C中,string类型可以看作char的数组。保存的是数组第一个元素的地址。那么对于真正的数组,也可以如lua使用rust代码--第二期 中处理字符串一样,处理对象数组。

示例

lib.rs

use std::ffi::CString;
use std::os::raw::{c_char, c_int};

//rust struct
#[derive(Deserialize,Debug)]
struct HostInfo {
	ip:String,
	port:u32,
}

#[derive(Debug)]
#[repr(C)]
pub struct CHostInfo {
    ip: *const c_char,
    ip_len: c_int,
    port: c_int,
}

fn get_info() -> Result<Vec<HostInfo>, reqwest::Error>{
//get data through api by reqwest
	let res: Vec<HostInfo> = reqwest::Client::new()
			.get("http://example.com/api/host/")
			.send()?
			.json()?;
		Ok(res)
}

#[no_mangle]
pub extern "C" fn get_all_data(len: *mut u32) -> *mut CHostInfo{
	let res = get_info().expect("http request fail");
	let mut data:Vec<CHostInfo> = res.into_iter()
		.map(|info| {
			let ip_cs = CString::new(info.ip.as_str()).unwrap();
			let ip = ip_cs.as_ptr();
			let ip_len = info.ip.len() as c_int;
			std::mem::forget(ip_cs);
			CHostInfo {
				ip: ip,
				ip_len:ip_len,
				port: info.port as c_int,
			}
		})
		.collect();
	let ptr = data.as_mut_ptr();
	unsafe {
		*len = data.len() as u32;
	}
	std::mem::forget(data);
	ptr
}

lua

ffi = require("ffi")
ffi.cdef[[
	typedef struct {
		char * ip;
		int    ip_len;
		int    port;
	} hostinfo_t;
	hostinfo_t * get_all_data(int*);
]]
rust_lib = ffi.load("./libexample.so")
function get_all_data()
	local intPtr = ffi.typeof("int[1]")
	local len = intPtr()
	local data = rust_lib.get_all_data(len)
	local res ={}
	for i=0,len[0]-1 do
		res[i] = {}
		res[i]["ip"] = ffi.string(data[i].ip,data[i].ip_len)
		res[i]["port"] = data[i].port
	end
	return res
end

转载于:https://my.oschina.net/u/3703365/blog/3083688

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值