This repo demonstrates how to use .NET 7's Native AOT feature to build a native DLL that can be called from other languages, such as Java and Python.
In the .csproj
file add <PublishAot>true</PublishAot>
(see example)
Associate the C# native functions with the [UnmanagedCallersOnly]
attribute (see example)
For these examples the native DLL is published to /native-demo/native-c#.dll
:
dotnet publish ./_native-c#/ -r win-x64 -o /native-demo
Load the library at runtime and call the native functions. See examples in:
All examples showcase using native functions that:
- prints a message to the console,
- returns a 32-bit integer (
7 + 2
,7 - 2
), - returns a 64-bit double (
7 * 2
,7 / 2
), - modifies an array of 64-bit doubles (
array[i] = (i * 2) + 0.5
)
The output should look something like:
Hello from native code written in C#!
9
5
14.0
3.5
[0.5, 2.5, 4.5, 6.5, 8.5]