Memory allocation and writing to incomplete array field generated by bindgen

⚓ rust    📅 2025-05-21    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 39 days ago. The information described in this article may have changed.

I am trying to write to an __IncompleteArrayField generated by bindgen for interaction with a C library.

Following the advice in another post, there is something I am not quite doing right as the snippet...

slice.copy_from_slice(&items);

... fails in runtime with the error:

thread 'test' panicked at library/core/src/panicking.rs:218:5:
unsafe precondition(s) violated: ptr::copy_nonoverlapping requires that both pointer arguments are 
aligned and non-null and the specified memory ranges do not overlap

The full example is available in the Rust playground, but here is the part relevant to the issue:

let item_layout = Layout::array::<Item>(2)?;
let buffer = alloc(item_layout) as *const [Item; 0];
let mut arr = __IncompleteArrayField(PhantomData, *buffer);

let items = [Item::new("apple"), Item::new("banana")];
let slice = arr.as_mut_slice(items.len());
slice.copy_from_slice(&items); // <-- panics

What am I doing wrong?

2 posts - 2 participants

Read full topic

🏷️ rust_feed