1

I'm using a dynamically loaded C library that requires me to allocate and manage memory at runtime for opaque objects (i.e. structures that my program only accesses indirectly). Currently I'm using code that looks similar to this, where GetObjectSize and InitalizeObject are foreign functions:

unsafe {
    // Ask the library for the size.
    let mut size: usize = 0;
    let mut success = GetObjectSize(&mut size);
    if success && size > 0 {
        // allocate and zero fill the memory, using a Vec.
        let mut ffi_obj = vec![0u8; size];
        // pass ffi_obj to the C library.
        success = InitalizeObject(ffi_obj.as_ptr(), &size);
        // ...etc, etc.

Presumably I should be wrapping the Vec in a struct so that it has a less generic type? I'm not sure Vec is right in the first place as I'd always want a fixed size which makes having a separate length and capacity redundant.

So what's the preferred way to manage the memory?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ChrisD
  • 3,378
  • 3
  • 35
  • 40
  • See also [How do I use the Rust memory allocator for a C library that can be provided an allocator?](https://stackoverflow.com/q/39250335/155423) – Shepmaster May 31 '17 at 17:07

0 Answers0