Open3

.net9でNativeAotのライブラリを試す

chobi_echobi_e

.net9であんまりNativeAOT試している記事がないなーということでメモ。

dotnet new classlib -o example
cd example
echo 'namespace example;

using System.Runtime.InteropServices;

public static class NativeLib
{
    [UnmanagedCallersOnly(EntryPoint = "add")]
    public static int Add(int a, int b)
    {
        return a + b;
    }
}
' > Class1.cs

dotnet publish -c Release --ucr
cp bin/Release/net9.0/osx-arm64/publish/example.dylib .
nm -g example.dylib | grep add

echo '#ifndef EXAMPLE_H
#define EXAMPLE_H
#ifdef __cplusplus
extern "C" {
#endif
int add(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
' > example.h

echo 'import Foundation
let result = add(3, 5)
print("Result: \(result)")
' > main.swift

swiftc -import-objc-header example.h main.swift -o main -Xlinker example.dylib
./main
Result: 8
chobi_echobi_e

[UnmanagedCallersOnly(EntryPoint = "add")]を使うとテキストセクションに配置されるもんだと思っていたのでなんかおかしいな、と思っていたけれどスタティックセクションに配置されるであってるらしい。

 nm -g example.dylib | grep add
000000000009d450 S _add
                 U _dladdr
                 U _pthread_get_stackaddr_np

今回のサンプルはdlopenを使わないパターンだけどこれで.net9を使ったライブラリを他の言語で使いやすくなりました。

chobi_echobi_e

ネイティブにAOTコンパイルするというだけなので劇的に速くなるとかそういったサイドエフェクトはないようです。実際試してみるとほぼ同じかちょっと遅いかも?ぐらいの変化しか見当たりませんでした。