-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Labels
Milestone
Description
Description
The following code results in Fatal error. Invalid Program: attempted to call a UnmanagedCallersOnly method from managed code..
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
unsafe class Program
{
[DllImport("NativeDll", CallingConvention = CallingConvention.Cdecl)]
public static extern void set_callback(delegate* unmanaged[Cdecl]<int, void> callback);
[DllImport("NativeDll", CallingConvention = CallingConvention.Cdecl), SuppressGCTransition]
public static extern void set_value(void* unused, int value);
[DllImport("NativeDll", CallingConvention = CallingConvention.Cdecl)]
public static extern void call_callback(void* unused, int unused2);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void PrintInt(int value)
{
Console.WriteLine(value);
Console.ReadKey(true);
}
static void Main()
{
set_callback(&PrintInt);
set_value(null, 1234);
call_callback(null, 1234); // crashes here!
}
}void (*globalCallback)(int value) = nullptr;
int globalValue = 0;
extern "C" __declspec(dllexport) void set_callback(void (*callback)(int value)) {
globalCallback = callback;
}
extern "C" __declspec(dllexport) void set_value(void*, int value) {
globalValue = value;
}
extern "C" __declspec(dllexport) void call_callback(void*, int) {
globalCallback(globalValue);
}Configuration
.NET Version: 5.0.101
OS: Windows 10 (18363.1256)
Architecture: x64
Regression?
N/A, since a lot of this stuff didn't even exist on 3.1.
Other information
Notably, if at least one of the following is true, then the crash no longer occurs:
- x86 is used instead of x64.
SuppressGCTransitionis removed fromset_value.set_valueis modified to take alonginstead of anint.call_callbackis modified to take alonginstead of anint.- The code is run under Release mode.