primix
primix

Reputation: 405

How do I write a number larger than u8 to a pointer?

Doing some allocation with the alloc crate and I have stumbled upon a problem. As alloc returns a u8 pointer, I'm not able to write integers larger than 255 to that address. How would I fix that?

let ps = alloc(Layout::from_size_align(4096, 8).unwrap());
ps.write(399); // this line gives out of range error

Upvotes: 1

Views: 351

Answers (2)

vallentin
vallentin

Reputation: 26157

You could do that by casting it to another pointer type, e.g. *mut u32. You can do that by calling cast(), i.e. ps.cast::<u32>(), which is the same as ps as *mut u32. Then after that you can write() or assign to the reinterpreted pointer.

let layout = Layout::from_size_align(4096, 8).unwrap();
let ps = alloc(layout);

ps.cast::<u32>().write(399);
assert_eq!(*ps.cast::<u32>(), 399);

*ps.cast::<u32>() = 399;
assert_eq!(*ps.cast::<u32>(), 399);

*(ps as *mut u32) = 399;
assert_eq!(*(ps as *const u32), 399);

dealloc(ps, layout);

Upvotes: 2

Angelicos Phosphoros
Angelicos Phosphoros

Reputation: 3057

You need to cast pointer to needed type. Alloc is low level, it works with just "memory" so uses u8 because it is most close to meaning of "raw bytes".

let ps = alloc(Layout::from_size_align(4096, 8).unwrap());
let ps = ps as *mut MyTargetType;

// Use ps here
// ....

let ps = ps as *mut u8;
dealloc(ps, Layout::from_size_align(4096, 8).unwrap());

Upvotes: 2

Related Questions