Search code examples
rustffi

Calculate distance between two raw pointers


Some C interfaces return pointer to end of buffer. So then I need to convert the range to a slice. But slice can only be created from pointer and count. So how do I get the count.

Writing end - start simply gives me error: binary operation `-` cannot be applied to type `*mut i8` and std::ptr::PtrExt only has offset method to calculate end from the offset, but not the inverse operation.


Solution

  • A raw pointer can be cast to usize; you can then perform subtraction on those.

    end as usize - start as usize