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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

ZeroMemory
Member
MEMBER
Rep: 75
Join Date: Oct 2024
Posts: 32
Thanks: 18
4y ago · Aug 22, 2021 3:03 PM
#1
What are the advantages of using the new [LibraryImport] source generator over traditional [DllImport] in .NET 7/8?
ZeroMemory · Always experimenting
The following users thanked ZeroMemory for this post:
RustMechanic
Unity & IL2CPP Reverser
VIP
Rep: 295
Join Date: Nov 2022
Posts: 32
Thanks: 74
4y ago · Aug 22, 2021 4:42 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.
RustMechanic | IL2CPP & Unity Engine Analysis
NoRecoilDev
Input & Recoil Math
MEMBER
Rep: 130
Join Date: Nov 2024
Posts: 20
Thanks: 32
4y ago · Aug 23, 2021 5:42 PM
#3
It also eliminates the runtime JIT overhead on the first native function invocation. Highly recommended for any new P/Invoke code.
NoRecoilDev | Smoothing Algorithms & Input Events