Replies: 1 comment 1 reply
-
Be aware of potential GC that moves the data, so alignment may not hold when not being pinned. Get the address of data, then do a modulo against the desired alignment. E.g. static unsafe bool IsAligned(ReadOnlySpan<byte> span, nuint alignmentInBytes)
{
// Note: GC can happen anytime, it's not deterministic from user PoV, so the address may change anytime too as there's no indication that data is pinned in memory
ref byte r = ref MemoryMarshal.GetReference(span);
void* ptr = Unsafe.AsPointer(ref r);
return (nuint)ptr % alignmentInBytes == 0;
} or saver when data is already pinned ( static unsafe bool IsAligned(void* ptr, nuint alignmentInBytes)
{
return (nuint)ptr % alignmentInBytes == 0;
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a method that takes a Span of bytes, and need to operate on the data as ulongs. Currently, I'm copying the input to a 64-bit aligned buffer. What's the best way to test if the input buffer is already aligned, in order to use MemoryMarshal.Cast and skip the copy?
Beta Was this translation helpful? Give feedback.
All reactions