Skip to content

Potential Perf Gain: Use LibraryImport instead of DllImport when using .NET 7 #105

@nikeee

Description

@nikeee

When using .NET 7, there is a new attribute that can be used to mark p/invokes:
https://learn.microsoft.com/en-us/dotnet/standard/native-interop/pinvoke-source-generation

The API is kinda similar:

[DllImport(
    "nativelib",
    EntryPoint = "to_lower",
    CharSet = CharSet.Unicode)]
internal static extern string ToLower(string str);

becomes

[LibraryImport(
    "nativelib",
    EntryPoint = "to_lower",
    StringMarshalling = StringMarshalling.Utf16)]
internal static partial string ToLower(string str);

The key difference is that the code used to marshal the parameters is emitted during compile-time instead of run-time. This is faster but also opens the ability to do native AOT compilations.

I think d2dlib uses .NET 6, so this might not be relevant yet. But it might be for the next major LTS version.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions