ffi_string_from_buffer

Function ffi_string_from_buffer 

Source
pub unsafe fn ffi_string_from_buffer<F>(
    buffer_size: usize,
    ffi_call: F,
) -> Option<String>
where F: FnOnce(*mut i8, isize) -> bool,
Expand description

Retrieves a string from an FFI function that writes to a buffer.

This is a common pattern in Objective-C FFI where a function:

  1. Takes a buffer pointer and length
  2. Writes a null-terminated string to the buffer
  3. Returns a boolean indicating success

§Arguments

  • buffer_size - Size of the buffer to allocate
  • ffi_call - A closure that takes (buffer_ptr, buffer_len) and returns success bool

§Returns

  • Some(String) if the FFI call succeeded and the string was valid UTF-8
  • None if the FFI call failed or returned an empty string

§Safety

The caller must ensure the ffi_call closure properly writes a null-terminated string to the provided buffer and does not write beyond the buffer length.

§Example

use screencapturekit::utils::ffi_string::ffi_string_from_buffer;

let result = unsafe {
    ffi_string_from_buffer(64, |buf, len| {
        // Simulate FFI call that writes "hello" to buffer
        let src = b"hello\0";
        if len >= src.len() as isize {
            std::ptr::copy_nonoverlapping(src.as_ptr(), buf as *mut u8, src.len());
            true
        } else {
            false
        }
    })
};
assert_eq!(result, Some("hello".to_string()));