Are method locals "fixed"? #101937
-
I'm trying to write some convenience wrappers around CsWin32, and I'm hitting an issue with reference/pointer conversion. Are method local variables considered "fixed"/"GC safe" in the below? void MethodA(Span<byte> buffer)
{
NativeOverlapped overlapped = new();
// ...
UseOverlapped(buffer, ref overlapped);
}
void MethodB(Span<byte> buffer, scoped ref NativeOverlapped lpOverlapped)
{
// CsWin32 wrapper around Win32's ReadFile
bool result = PInvoke.ReadFile(handle, buffer, null, (NativeOverlapped*)Unsafe.AsPointer(ref lpOverlapped);
// ...
} Or does void MethodB(Span<byte> buffer, scoped ref NativeOverlapped lpOverlapped)
{
bool result;
fixed (NativeOverlapped* lpOverlappedLocal = &lpOverlapped)
{
result = PInvoke.ReadFile(handle, buffer, null, lpOverlappedLocal);
}
// ...
} It's my understanding that things on the stack are "rooted" by their nature, so |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
While it is safe in this case, it is generally recommended to avoid relying on such details and express intentions directly via |
Beta Was this translation helpful? Give feedback.
While it is safe in this case, it is generally recommended to avoid relying on such details and express intentions directly via
fixed
.Unsafe.AsPointer
is one of the most dangerous API and, sadly, too often introduces so called gc holes.