CodeBlanks Logo Icon CodeBlanks

Function pointer

C# course · Expert · Lesson 17/47

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 = &Square;. Call it with int r = fp(6); and print Console.WriteLine(r);.

Show example solution
delegate* unmanaged<int, int> fp = &Square; 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 = &Square;
        int r = fp(6);
        Console.WriteLine(r);
    }
}

Test yourself

  1. 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.

  2. Match the delegate* syntax

    delegate*
    Function pointer
    unmanaged
    Unmanaged calling convention
    &Function
    Function address
    fp(5)
    Pointer call
  3. delegate* declaration

    delegate* unmanaged<int, int> fp = ____Function;
    Show answer
    delegate* unmanaged<int, int> fp = &Function;

All lessons in Expert