Are method locals "fixed"? #101937
Answered
by
EgorBo
colejohnson66
asked this question in
Q&A
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.
Answered by
EgorBo
May 6, 2024
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.
4 replies
Answer selected by
colejohnson66
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.