Repository navigation
EN CSharp Keyword unmanaged function pointer calling convention
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
unmanaged on the delegate* type specifies an unmanaged call convention. Without a list, the platform agreement is used; Cdecl can be explicitly specified in square brackets. A static C# method with UnmanagedCallersOnly is called via a compatible unmanaged pointer instead of a normal managed call. The project allows unsafe blocks.
Save this example separately as Example.cs. Run it independently of the other examples on this page.
Example.cs:
// PROJECT-EXAMPLE
unsafe
{
delegate* unmanaged[Cdecl]<int, int> twice = &Tools.Twice;
System.Console.WriteLine(twice(4));
}
static class Tools { [System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] public static int Twice(int value) => value * 2; }Enable <AllowUnsafeBlocks>true</AllowUnsafeBlocks> in the project. The pointer is valid only within the shown scope.
Result:
8
delegate* unmanaged<int, int> operation = &Transform;
delegate* unmanaged[Cdecl]<int, int> callback = &TransformCdecl;File Example.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
</Project>File Program.cs:
using System;
using System.Runtime.InteropServices;
internal static unsafe class Program
{
public static void Main()
{
delegate* unmanaged<int, int> doubleValue = &DoubleValue;
Console.WriteLine(doubleValue(12));
}
[UnmanagedCallersOnly]
private static int DoubleValue(int value) => value * 2;
}Result:
24
File Example.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
</Project>File Program.cs:
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal static unsafe class Program
{
public static void Main()
{
delegate* unmanaged[Cdecl]<int, int, int> callback = &Difference;
int result = InvokeCallback(callback, 14, 5);
Console.WriteLine(result);
}
private static int InvokeCallback(delegate* unmanaged[Cdecl]<int, int, int> callback,
int left, int right) => callback(left, right);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Difference(int left, int right) => left - right;
}Result:
9
Official source: Microsoft Learn.
ClassicUO — Bad Newbie & C# Scripts IDE