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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

PacketSniffer
Network Protocols & Sockets
MEMBER
Rep: 195
Join Date: Sep 2024
Posts: 22
Thanks: 49
2y ago · May 13, 2024 4:48 PM
#1
What are the advantages of using the new [LibraryImport] source generator over traditional [DllImport] in .NET 7/8?
PacketSniffer | Network Protocols & Winsock SPI
The following users thanked PacketSniffer for this post:
ParanormalDev
MelonLoader / BepInEx Dev
MEMBER
Rep: 230
Join Date: Sep 2023
Posts: 21
Thanks: 58
2y ago · May 13, 2024 7:05 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.
ParanormalDev | MelonLoader & ImGui Modding
CodeVoyager
C++ / Systems Dev
MEMBER
Rep: 57
Join Date: Apr 2023
Posts: 7
Thanks: 39
2y ago · May 14, 2024 9:05 PM
#3
It also eliminates the runtime JIT overhead on the first native function invocation. Highly recommended for any new P/Invoke code.
CodeVoyager · C++ / Systems Dev
Exploring modern C++20/23, template metaprogramming, and Lin...