runtime icon indicating copy to clipboard operation
runtime copied to clipboard

UnmanagedCallersOnly throws an exception on blittable struct return types

Open withkittens opened this issue 5 years ago • 3 comments

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;
     }

withkittens avatar Apr 13 '21 12:04 withkittens

/cc @jkoritzinsky @elinor-fung

AaronRobinsonMSFT avatar Apr 13 '21 16:04 AaronRobinsonMSFT

This is a duplicate of https://github.com/dotnet/runtime/issues/35928 and has been addressed for .NET 6.0

jkoritzinsky avatar Apr 13 '21 23:04 jkoritzinsky

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.

AaronRobinsonMSFT avatar Apr 13 '21 23:04 AaronRobinsonMSFT