NativeAOT and ctypes: from the linker error to a native call

The fourth way is the one that removes the transports: compile the core to a native shared library and call its function from Python through ctypes. The .NET SDK supports it with NativeAOT, and the C# side needs one attribute. Inside this container the publish stops at the linker, and the page shows that error; on the host of the container, with the toolchain installed, the same sources were published and called, and the page shows those real results too.

The attempt

The project was restored, the ILCompiler package was downloaded, the core and the library compiled, and the publish stopped at the linker. clang and gcc are not in this image, which the C# course records in the note of every page. The real output:

dotnet publish -c Release -r linux-musl-x64
echo "status: $?"

  Aot -> /tmp/r12/project/aot/bin/Release/net10.0/linux-musl-x64/Aot.dll
/home/agent/.nuget/packages/microsoft.dotnet.ilcompiler/10.0.15/build/Microsoft.NETCore.Native.Unix.targets(316,5): error : Platform linker ('clang' or 'gcc') not found in PATH. Ensure you have all the required prerequisites documented at https://aka.ms/nativeaot-prerequisites. [/tmp/r12/project/aot/Aot.csproj]
status: 1

The error is the environment and not the code: the restore of Microsoft.DotNet.ILCompiler succeeded in 30.38 seconds, and the publish reached the native link step before it stopped.

What the host needed

Three packages and a network: the linker and the C development headers for the native build, zlib-dev for what the runtime links against, and a route to NuGet for the ILCompiler package, which is not in the image. The host of this container, which runs the same image, ran:

apk add --no-cache clang build-base zlib-dev

The same sources of the rest of this page were then published with:

dotnet publish aot/Aot.csproj -c Release -r linux-musl-x64 -p:NuGetAudit=false

The publish printed no error and exited zero. The library it wrote is aot/bin/Release/net10.0/linux-musl-x64/publish/Aot.so, 1 192 360 bytes.

The project

Two properties make a class library a native shared library: PublishAot and NativeLib=Shared. The reference to the core is the same as in the other hosts:

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <PublishAot>true</PublishAot> <NativeLib>Shared</NativeLib> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\src\Core\Core.csproj" /> </ItemGroup> </Project>

The exports

A method marked [UnmanagedCallersOnly] is callable from C, and its parameters must be blittable: pointers and integers, not strings. The export takes a UTF-8 request and writes a UTF-8 answer into a buffer the caller owns, and returns the number of bytes or −1 when the buffer is too small:

using System; using System.Runtime.InteropServices; using System.Text; using Core; namespace Aot; public static unsafe class Exports { /// <summary>Prices one UTF-8 request line and writes a UTF-8 answer.</summary> [UnmanagedCallersOnly(EntryPoint = "price_line")] public static int PriceLine(byte* request, byte* answer, int capacity) { var line = Marshal.PtrToStringUTF8((IntPtr)request) ?? ""; var text = Pricing.Process(line); var bytes = Encoding.UTF8.GetBytes(text); if (bytes.Length + 1 > capacity) { return -1; } bytes.CopyTo(new Span<byte>(answer, bytes.Length)); answer[bytes.Length] = 0; return bytes.Length; } }

The caller

The Python caller declares the signature and passes two buffers:

#!/usr/bin/env python3 """Call the NativeAOT shared library through ctypes.""" import ctypes from pathlib import Path LIB = Path(__file__).resolve().parent / "bin" / "Release" / "net10.0" / "linux-musl-x64" / "publish" / "Aot.so" library = ctypes.CDLL(str(LIB)) library.price_line.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int) library.price_line.restype = ctypes.c_int for line in (b"sku=pen qty=2 unit=1.50", b"sku=pen qty=0 unit=1.50"): answer = ctypes.create_string_buffer(128) size = library.price_line(line, answer, len(answer)) print(size, answer.value.decode())

Run on the host, outside the default container

With the library published, the caller of the previous section is the whole test. python3 aot/call.py printed two lines: the number of bytes the export wrote and the answer it wrote, for the valid request and for the invalid one:

17 ok 3.00 0.60 3.60
24 err qty must be 1 to 100

The 17 and the 24 are the int the C# export returns: the length of the UTF-8 answer, without its terminator. The answers themselves are the answers of the same core the other pages call, which is the point of the exercise.

The call was then timed through ctypes, five runs of twenty thousand calls each, on the host with the toolchain installed and Python 3.14.10:

WaySeries (µs per call)MinMedian
the native library through ctypes3.42, 3.49, 3.50, 3.52, 4.783.423.50

That run is a separate run from the three numbers of the timing page, which were measured in this container with twenty calls per series; the two pages do not divide one by the other. What they say together is the shape of the fourth way: a native call is in microseconds, where the transports are in milliseconds or tens of milliseconds.

The next page tests the Python layer, the one after it tests the C# core, and the last one is the image that would deploy the whole project.

Exercises

  1. Explain why the export takes pointers and not strings.
  2. Add a free export that releases a buffer the library allocated.
  3. Run the two lines of the caller against the library, then change the buffer to ten bytes and explain the answer of the export.
  4. Compare the design with the daemon: what does a native library remove, and what does it add?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does NativeAOT need that this image lacks?

    Answer

    A platform linker, clang or gcc

    The measured error names the linker.

  2. What did the restore of the ILCompiler package do?

    Answer

    It succeeded, in 30.38 seconds

    The page says the restore succeeded and the link failed.

  3. What does this program print? Console.WriteLine("clang".Length > 0);

    Answer

    True

    A clang or gcc is what the publish asks for.

  4. Which property makes the library native?

    Answer

    NativeLib=Shared with PublishAot

    The project file of the page sets both.

  5. What does this program print? var answer = "ok"; Console.WriteLine(answer.Length + 1);

    Answer

    3

    The export returns the number of bytes, which for "ok" is two plus the terminator, and the page counts the answer of a small buffer.

  6. Why are the parameters of the export pointers?

    Answer

    An unmanaged caller has no .NET string type, so strings cross as UTF-8 bytes

    The page explains the blittable rule.

  7. What did the publish need that this container does not have?

    Answer

    clang or gcc with the C headers, and a route to NuGet for the ILCompiler package

    The host installed the toolchain and then published the library.

  8. What does this program print? var capacity = 2; var needed = 5; Console.WriteLine(needed + 1 > capacity ? -1 : needed);

    Answer

    -1

    A buffer that is too small is the -1 of the export contract.

  9. Why can an UnmanagedCallersOnly method not be called from managed code?

    Answer

    It is compiled for the unmanaged boundary only

    The attribute defines a native entry point.

  10. When is a native library the right design?

    Answer

    When the caller cannot host .NET, such as Python or a game engine

    For a .NET host the daemon or the API is simpler.

The C# code on this page was built with the .NET SDK 10.0.303 and the Python code was run with Python 3.14.10, on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.

Article author: Arthur Isaev