Function pointer
Learn unmanaged function pointers with delegate*.
delegate* (function pointer)
Since C# 9 you can define an unmanaged function pointer with delegate*. delegate* unmanaged<int, int> is a C-style function pointer; it is much faster than a delegate because the runtime does not marshal.
It is valid only in an unsafe context, taken with & and called with (). It is preferred for high-performance callbacks instead of P/Invoke.
Calling a delegate*
To call a delegate* you first need a function address: delegate* unmanaged<int, int> fp = &Function;. Then call it with int r = fp(5);.
Function pointers must be inside an unsafe block; on AOT compilers they are far more efficient than delegates. This is preferred in game engines and audio processing scenarios.
Exercise Call Square via delegate*
Define [UnmanagedCallersOnly] static int Square(int n) => n * n;. Make Main unsafe. Take the function pointer with delegate* unmanaged<int, int> fp = □. Call it with int r = fp(6); and print Console.WriteLine(r);.
Show example solution
delegate* unmanaged<int, int> fp = □ int r = fp(6); Console.WriteLine(r);
Example solution:
using System;
using System.Runtime.InteropServices;
class Program
{
[UnmanagedCallersOnly]
static int Square(int n) => n * n;
static unsafe void Main()
{
delegate* unmanaged<int, int> fp = □
int r = fp(6);
Console.WriteLine(r);
}
}
Test yourself
-
What does delegate* represent?
- A Delegate class
- A generic method
- An unmanaged function pointer
- An event handler
Show answer
An unmanaged function pointer — Correct. delegate* is an unmanaged function pointer.
-
Match the delegate* syntax
- delegate*
- Function pointer
- unmanaged
- Unmanaged calling convention
- &Function
- Function address
- fp(5)
- Pointer call
-
delegate* declaration
delegate* unmanaged<int, int> fp = ____Function;Show answer
delegate* unmanaged<int, int> fp = &Function;