UnmanagedCallersOnly throws an exception on blittable struct return types
Description
[UnmanagedCallersOnly] throws an exception if a return type is blittable struct:
struct BOOL
{
public uint value;
}
unsafe class Program
{
[DllImport("User32.dll")]
static extern bool EnumWindows(delegate* unmanaged<IntPtr, IntPtr, BOOL> lpEnumFunc, IntPtr lParam);
static void Main(string[] args) {
// System.InvalidProgramException: Non-blittable parameter types are invalid for UnmanagedCallersOnly methods.
// at Program.EnumWindows(IntPtr lpEnumFunc, IntPtr lParam)
EnumWindows(&EnumWindowsProc, IntPtr.Zero);
}
[UnmanagedCallersOnly]
static BOOL EnumWindowsProc(IntPtr hwnd, IntPtr lParam) {
return new BOOL { value = 1 };
}
}
BOOL is in fact blittable.
However, if I change the return types of functions to uint, everything works.
Another confusing thing about the exception is that it mentions parameter types but the issue is in a return type. Maybe it would be possible to show a problematic type in the message?
Configuration
- .NET 5.0.102
- Windows 10 20H2 19042.746
- x64
Regression?
I don't know.
Other information
A workaround is to use a primitive return type instead of a struct:
- static extern bool EnumWindows(delegate* unmanaged<IntPtr, IntPtr, BOOL> lpEnumFunc, IntPtr lParam);
+ static extern bool EnumWindows(delegate* unmanaged<IntPtr, IntPtr, uint> lpEnumFunc, IntPtr lParam);
...
- static BOOL EnumWindowsProc(IntPtr hwnd, IntPtr lParam) {
- return new BOOL { value = 1 };
+ static uint EnumWindowsProc(IntPtr hwnd, IntPtr lParam) {
+ return 1;
}
/cc @jkoritzinsky @elinor-fung
This is a duplicate of https://github.com/dotnet/runtime/issues/35928 and has been addressed for .NET 6.0
Since this isn't a regression, was considered in the referenced issue for .NET 5 and rejected, I am going to close this since it is fixed in .NET 6.