I may be going about this the wrong way because I have not done much pointer arithmetic in the past (and it may not even be necessary).
However, given a pointer in Swift (of type UnsafeMutableRawPointer
), I would like to get the nearest (rounding down) page-aligned address to it. This is in order to synchronise some memory mapped data using msync
Basically, I am trying to migrate some Objective C (well, basically C) code which looks like this:
int pageSize = getpagesize();
void *address = [some bytes];
size_t pageIndex = (size_t)address / pageSize;
void *pageAlignedAddress = (void *)(pageIndex * pageSize);
so far in Swift I have something like:
let pageSize: Int = Int(getpagesize())
let bytes: UnsafeMutableRawPointer = [some bytes]
let pageIndex: Int = Int(bytes) / pageSize
let pageAlignedAddress: UnsafeMutableRawPointer = UnsafeMutableRawPointer(pageIndex * pageSize)
Obviously the last two lines of my Swift code do not compile because I am mixing types and using non-existent initialisers. But I cannot see how to shift my existing UnsafeMutableRawPointer
to be page-aligned, nor can I see any methods on the type which might assist me in this.
Perhaps this is not even necessary for the Swift types and they are always page aligned…
Seems you just need to know what initializers
Int
andUnsafeMutableRawPointer
have.Int
init(bitPattern: UnsafeMutableRawPointer?)
UnsafeMutableRawPointer
init?(bitPattern: Int)
Int
has an initializer takingUnsafeMutableRawPointer?
, andUnsafeMutableRawPointer
has an initializer takingInt
. Why don't you use them?