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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

ReflectPro
Reflection & Roslyn
MEMBER
Rep: 355
Join Date: Mar 2022
Posts: 9
Thanks: 75
5y ago · Feb 13, 2021 6:21 PM
#1
What are the advantages of using the new [LibraryImport] source generator over traditional [DllImport] in .NET 7/8?
ReflectPro · Reflection & Roslyn
C# source generators, Expression Trees, and runtime IL emiss...
The following users thanked ReflectPro for this post:
LinQ_Lover
C# Developer
MEMBER
Rep: 313
Join Date: Jul 2020
Posts: 8
Thanks: 27
5y ago · Feb 13, 2021 7:36 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.
LinQ_Lover · C# Developer
Clean code, fluent LINQ expressions, and expressive C# patte...
PInvokeMaster
Interoperability Specialist
VIP
Rep: 247
Join Date: Feb 2021
Posts: 6
Thanks: 83
5y ago · Feb 14, 2021 1:36 AM
#3
It also eliminates the runtime JIT overhead on the first native function invocation. Highly recommended for any new P/Invoke code.
PInvokeMaster · Interoperability Specialist
P/Invoke, NativeAOT, C# to C++ native interoperability, and ...