Home / Forums / C# P/Invoke: DllImport vs LibraryImport Source Generators in .NET 7+ [Discussion #7]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

C# P/Invoke: DllImport vs LibraryImport Source Generators in .NET 7+ [Discussion #7]

UI_Wizard
ImGui Widget Dev
MEMBER
Rep: 72
Join Date: Feb 2021
Posts: 6
Thanks: 95
5y ago · Feb 22, 2021 11:57 AM
#1
What are the advantages of using the new [LibraryImport] source generator over traditional [DllImport] in .NET 7/8?
UI_Wizard · ImGui Widget Dev
Writing complex custom ImGui widgets: color pickers, curve e...
The following users thanked UI_Wizard for this post:
StackUnwinder
Debugging & Profiling
MEMBER
Rep: 145
Join Date: Jun 2025
Posts: 6
Thanks: 16
5y ago · Feb 22, 2021 2:30 PM
#2
Traditional [DllImport] uses runtime IL stub generation and reflection marshaling. [LibraryImport] generates C# marshaling code at compile time! It is faster, fully AOT-compatible (NativeAOT), and allows you to inspect the exact marshaling code generated in your IDE.
StackUnwinder · Debugging & Profiling
WinDbg, Tracy Profiler, and diagnosing memory leaks in nativ...
SourceGenDev
C# Tooling
MEMBER
Rep: 158
Join Date: Jan 2020
Posts: 8
Thanks: 79
5y ago · Feb 23, 2021 7:30 PM
#3
It also eliminates the runtime JIT overhead on the first native function invocation. Highly recommended for any new P/Invoke code.
SourceGenDev · C# Tooling
Metaprogramming with C# 9+ Source Generators and Roslyn Anal...