Search code examples
c#.net-coredllnativenative-aot

How to use a dll generated in c# and compiled using Native AOT in other .NET Projects?


Since I first heard about the introduction of Native AOT feature in .NET 7 and that it was usable on console executables and class libraries, I wanted to try out on some library projects I already had. Then, rised a problem I can't seem to workaround no matter the amount of research made. In fact after compiling successfully into a native dll, I don't know how to use it inside other .Net projects as it is no longer recognized as a .Net library type to be added as reference.

If anyone could enlighten me on how to access the methods compiled in that native dll from any other project in .Net, this could really mean a lot to me.

I have tried using the export attribute on public methods in the original library code to make them visible to external call. And then using import attribute on the caller project but nothing seem to work I can't see any public method from the generated dll.


Solution

  • Like the release of the console, add a class library project, and then define the method, but you need to add the UnmanagedCallersOnly feature and specify the EntryPoint:

    [UnmanagedCallersOnly(EntryPoint = "OutPut")]
    public static int OutPut()
    {
        return 1;
    }
    

    And turn on the AOT compilation option:

    <PublishAot>true</PublishAot>

    and then use the command line to publish

    dotnet publish -r win-x64

    Finally in your project call the function

    [DllImport("AOTDLL.dll")]
    public static extern int OutPut();
    

    Of course, this dll can also be used in C++,like this https://joeysenna.com/posts/nativeaot-in-c-plus-plus