lua使用rust代码(第二期)--String

lua使用rust代码--第二期

前言

lua本身提供来ffi库,来完成对C语言的对接(实际上是动态连接库*.so)。调用rust代码也是通过这个ffi。那么对于structstd::string::String,Vec\<struct\>,也因该保持其与C代码有相同的结果。

背景知识
对于数组在C中就是指向数组中第一个元素的指针。为了防止内存过界,所有数组操作必须获取数组的长度。在rust代码中数组的长度(len)和大小(cap)已经被封装。

std::string::String

string在C里就是char的指针。

rust


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

#[no_mangle]
pub extern "C" fn get_string(len *mut c_int) -> *const c_char{
	let rust_string = String::from("这时一个字符串");
	let c_string = CString::new(coco.remote_addr.as_str()).unwrap();
	len = rust_string.len() as c_int;//获取字符串长度
	let c_string_ptr = c_string..as_ptr();
	std::mem::forget(c_string);//避免被drop
	c_string_ptr
}

lua

ffi = require("ffi")
ffi.cdef[[
    char  * get_all_data(int*);
]]

local rust_lib = ffi.load("libexample.so")
local intPtr = ffi.typeof("int[1]")--初始化int*
local function get_string()
	local c_len = intPtr()
	local c_string = rust_lib.get_string(c_len)
	local lua_len = c_len[0]
	local lua_string =  ffi.string(c_string,lua_len)
	return lua_string
end
print(get_string())

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值