adawolfa/ffi-memory-stream

FFI memory stream wrapper.

1.2 2023-08-12 01:04 UTC

This package is auto-updated.

Last update: 2024-04-12 02:32:08 UTC


README

This library provides a PHP stream wrapper for direct memory access using standard stream functions. It's intended to be used by FFI wrappers as a method of providing safe, convenient and known way of accessing data.

Installation

composer install adawolfa/ffi-memory-stream

Usage

There's a memory_open() function, which creates a stream to the data from FFI pointer.

$ptr    = $ffi->get_buffer($size);
$stream = Adawolfa\MemoryStream\memory_open($ptr, 'r', $size);
$data   = fread($stream, 10);

You can make the stream read-only (r), write-only (w) or unrestricted (rw). The wrapper ensures that the user operates within the stream boundaries thanks to the $size argument, which is mandatory.

You, as a callee, should fclose() the stream explicitly once the pointer becomes invalid. Reading from or writing into such stream emits a warning, but unlike accessing the data via an invalid pointer, doesn't cause the process to crash, making it much easier for caller to debug.

Both 32-bit and 64-bit platforms are supported, little-endian is assumed.