getditto / safer_ffi

Write safer FFI code in Rust without polluting it with unsafe code

Home Page:http://getditto.github.io/safer_ffi

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Q: How to parse parameters of type Array

magicLaLa opened this issue · comments

I have an export function, how to parse the parameters of the array type in the parameter;
I don’t know if my writing is correct;

use safer_ffi::{prelude::*};

#[derive_ReprC]
#[repr(C)]
#[derive(Debug)]
pub struct FfiArray<'a> {
    pub data: *const f64,
    pub len: usize,
    _marker: std::marker::PhantomData<&'a [f64]>,
}

#[ffi_export]
pub fn my_push(array: FfiArray) {
    // let slice = std::slice::from_raw_parts(array.data, array.len);
    println!("my_push: {array:?}");
}

test.mjs

import ffi from "ffi-napi";
import ref from "ref-napi";
import ref_struct from "ref-struct-di";
import ref_array from "ref-array-di";

const StructType = ref_struct(ref);
const ArrayType = ref_array(ref);

const DoubleArray = ArrayType(ref.types.double);

const libm = ffi.Library("./target/release/wave_from_tools.dll", {
  my_push: ["void", [DoubleArray]]
});

libm.my_push(new DoubleArray([1.2, 2.2]));

Parsing failed:my_push: FfiArray { data: 0x3ff3333333333333, len: 4612136378390124954, _marker: PhantomData<&[f64]> }

Need to be changed like this:

#[ffi_export]
pub fn my_push<'xs>(array: c_slice::Ref<'xs, i32>) {
    // let p = array.as_slice().iter().max();
    println!("p: {array:?}"); // p: [1, 2, 3, 4, 5, 6, 7, 8]
}

test.mjs

const ArrayInt32List = StructType({
  ptr: Int32ArrayType,
  len: ref.types.int,
});
const libm = ffi.Library("./target/release/wave_from_tools.dll", {
  my_push: ["void", [ArrayInt32List]]
});

const tmpList = new Int32ArrayType([1,2,3, 4, 5, 6, 7, 8]);
const int32List = new ArrayInt32List({
  ptr: tmpList,
  len: tmpList.length,
});
libm.my_push(int32List);

Because passing pointers and sizes.

https://github.com/getditto/safer_ffi/blob/master/src/slice.rs#L282

Hey, your use-case seems more sutble than the usual ones, since you seem to be talking to node.js through N-API (which technically safer-ffi also kind of does on its own, but only internally (the API is not exposed to crates.io since it is very experimental)).

So, indeed, this issue would have been out of scope for safer-ffi-as-a-repo, so I am glad you sorted it out on your own 🙂

That being said, I'm always keen on hearing about usages of safer-ffi, and helping/discussing whenever it is possible.

I've very recently created a Discord server (currently empty 😅), so as to have a space for more informal conversations around safer-ffi usage. If you feel like dropping by there, to talk about your use-case, feel free!