Commit 01d16ad6

01d16ad62711Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 5 files · +2 added · ~3 modified

Description

feat(ffi): :float_array / :int_array specs for zero-copy bulk transfer

Closes #474. Two new FFI type specs that let C functions consume Spinel's contiguous Array storage as plain C pointers:

:float_array -> const double * (Array's .data) :int_array -> const int64_t * (Array's .data)

Length is a separate :size_t arg, symmetric to :str + strlen. The GC contract mirrors :str — call-duration lifetime; if the C side needs to keep the pointer, it has to copy. The caller is responsible for keeping the Array alive across the call.

Implementation: ffi_type_of / ffi_c_type_of recognize the new spec tokens; compile_ffi_func_call's arg-emit branch routes them to ((const double *)(<expr>)->data) (and the int64_t variant) rather than the generic cast applied to scalar specs. This is strictly additive — no existing FFI signatures change.

Test: a declare-only test exercises the analyze + codegen path. No portable libc/libm symbol takes const double * for a runtime end-to-end test; the toy_ruby_neural_network project (the issue's motivating case) provides the real callable side via tnn_upload_from_float_array.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
01d16ad62711
Parent
1ca17ac27e8d

docs/FFI.mdmodifiedView file

@@ -82,12 +82,21 @@
8282 | `:bool` | `int` | `bool` |
8383 | `:str` | `const char *` | `string` |
8484 | `:ptr` | `void *` | `ptr` |
85+| `:float_array` | `const double *` | `Array<Float>` (`.data` pointer) |
86+| `:int_array` | `const int64_t *` | `Array<Int>` (`.data` pointer) |
8587 | `:void` | `void` | `void` (return only) |
8688
8789 All integer types collapse to `mrb_int` (int64) inside Spinel and are
8890 cast to the declared C type at the call boundary. Floats collapse to
8991 `double` the same way.
9092
93+`:float_array` / `:int_array` hand the C side a pointer to the Spinel
94+Array's contiguous storage (`.data`). Length is **not** part of the
95+spec — pass it as a separate `:size_t` arg, same way as `:str` +
96+`strlen`. Lifetime is call-duration only: the GC may free the
97+underlying Array after the call returns, so the C side must not
98+stash the pointer (copy if it needs to).
99+
91100 ### `ffi_const :NAME, <int>`
92101
93102 Declares an integer constant accessible as `Module::NAME`. Pure