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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

DarkLogic
Game Logic & SDK Developer
MEMBER
Rep: 180
Join Date: Jun 2024
Posts: 28
Thanks: 41
5y ago · Aug 4, 2021 8:39 AM
#1
What are the advantages of using the new [LibraryImport] source generator over traditional [DllImport] in .NET 7/8?
DarkLogic | Virtual method tables & SDKs
The following users thanked DarkLogic for this post:
ApexPredator_
Source Engine Modder
VIP
Rep: 340
Join Date: May 2022
Posts: 23
Thanks: 88
5y ago · Aug 4, 2021 9:45 AM
#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.
ApexPredator_ · Source Engine Specialist
BoneMatrix_
CS2 & Skeleton Math
MEMBER
Rep: 190
Join Date: Aug 2024
Posts: 21
Thanks: 47
5y ago · Aug 5, 2021 3:45 PM
#3
It also eliminates the runtime JIT overhead on the first native function invocation. Highly recommended for any new P/Invoke code.
BoneMatrix_ · Source 2 Skeleton ESP & Hitboxes