有大佬熟悉 ffi 么,如何从 ffi 获取 array 返回值

2022-08-07 21:52:43 +08:00
 freehere
#[no_mangle]
pub extern "C" fn decode(raw: *const libc::c_char) -> *mut u32 {
    let str_raw = unsafe { CStr::from_ptr(raw) }.to_str().unwrap().to_string();
    let bytes_raw = hex::decode(str_raw).unwrap();
    let mut u8_fixed: [u32; 6] = Decode::decode(&mut &bytes_raw[..]).unwrap();
    let ptr = u8_fixed.as_mut_ptr();
    std::mem::forget(u8_fixed);
    ptr
}

nodejs code


let libm = ffi.Library(rootPath, {
   'decode': [ref.refType("uint"), ['string']],
}
let value = libm.decode("010000000200000003000000040000000500000006000000")

decode 的 value 返回值应该是 []uint{1,2,3,4,5,6} ,现在打印出 value 看起来像是个 buffer, 不知道怎么解析这个 buffer

1564 次点击
所在节点    Rust
8 条回复
nomagick
2022-08-07 22:01:01 +08:00
freehere
2022-08-08 08:24:00 +08:00
@nomagick 看过了 example 和 test ,测试了一下,还是没有搞出来
nomagick
2022-08-08 11:33:00 +08:00
@freehere 你这个函数返回的是 ref(array(uint)), 第一层是个指针,你拿到的 buffer 是指针的值,把它 deref(), 才是 array(uint)
freehere
2022-08-08 15:55:37 +08:00
k1263
2022-08-26 16:59:26 +08:00
Decode::decode 哪里来的?自己定义的吗?
freehere
2022-08-31 11:15:55 +08:00
k1263
2022-09-07 14:01:41 +08:00
@freehere
我的这一步会出错,CStr::from_ptr(raw).to_str(), 你的出错吗?

#[no_mangle]
pub extern "C" fn decode(raw: *const libc::c_char) -> *mut u32 {
if raw.is_null() {
return ptr::null_mut();
}
if let Ok(str_raw) = unsafe { CStr::from_ptr(raw).to_str() } {
println!("str_raw: {:?}", str_raw);
let bytes_raw = hex::decode(str_raw).unwrap();
let mut u8_fixed: [u32; 6] = Decode::decode(&mut &bytes_raw[..]).unwrap();
let ptr = u8_fixed.as_mut_ptr();
std::mem::forget(u8_fixed);
ptr
} else {
println!("str_raw fail");
return ptr::null_mut();
}

}

pub fn main() {
let raw = "010000000200000003000000040000000500000006000000";
let aa = decode(raw.as_ptr() as *const i8);
println!("{:?}", aa);
}
zhangyuang
111 天前

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/871291

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX