Home About Eric Topics SourceGear

2023-01-18 13:00:00

Silly

This is part of a series on Native AOT.
Previous -- Top -- Next


Native AOT produces libraries that can be called from any language that can call C.

C# is one such language.

Yes folks, that's right -- even though it is [probably] not useful, you can call into a Native AOT library from C# using P/Invoke:

using System;
using System.Runtime.InteropServices;

static class MulCsPinvoke
{
    [DllImport("mul")]
    static extern int multiply(int a, int b);

    public static void Main()
    {
        var c = multiply(7, 6);

        Console.WriteLine($"{c}");
    }
}

After we copy mul.dll into place, we can run it:

$ cp ../mul_cs/bin/Debug/net7.0/win-x64/publish/mul.dll .

$ dotnet run
42

The code for this blog entry is available at:

https://github.com/ericsink/native-aot-samples/tree/main/mul_cs_pinvoke