-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
Description
I am trying to access private members from an instance of a Guid (struct) but doing so throws the error supplied in the title.
I have discoved that using Unsafe.As<>() I can cast the struct to a dummy class and the extraction will work, though with some allocation overhead.
Reproduction Steps
var guid = Guid.NewGuid();
var dummy = Unsafe.As(guid);
ref var a = ref UnsafeAccessorClass.GetInt32FieldA(dummy); // Works
ref var alsoA = ref UnsafeAccessorClass.GetInt32FieldA(guid); // Throws
sealed class Dummy
{
private readonly int _a; // Field must be declared.
}
sealed class UnsafeAccessorClass
{
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_a")]
public extern static ref int GetInt32FieldA(Dummy dummy);
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_a")]
public extern static ref int GetInt32FieldA(Guid guid);
}
Expected behavior
No errors.
Actual behavior
Throws 'System.BadImageFormatException' occurred in Console.dll: 'Invalid usage of UnsafeAccessorAttribute.'
Regression?
No response
Known Workarounds
Cast struct to class using Unsafe.As()
Configuration
`dotnet --info
.NET SDK:
Version: 8.0.204
Commit: c338c7548c
Workload version: 8.0.200-manifests.9f663350
Runtime Environment:
OS Name: Windows
OS Version: 10.0.19045
OS Platform: Windows
RID: win-x64
Base Path: C:\Program Files\dotnet\sdk\8.0.204\
.NET workloads installed:
There are no installed workloads to display.
Host:
Version: 8.0.4
Architecture: x64
Commit: 2d7eea2
.NET SDKs installed:
8.0.204 [C:\Program Files\dotnet\sdk]
.NET runtimes installed:
Microsoft.AspNetCore.App 8.0.4 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.NETCore.App 8.0.4 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 8.0.4 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Other architectures found:
None
Environment variables:
Not set
global.json file:
Not found`
Other information
No response