Pages

Tuesday, November 15, 2022

CSharp Interop P/Invoke mechanism has change in .NET7 - LibraryImport replaces DLLImport



Major announcement at .NET CONF 2022 .NET7 which some of you many have missed,  replaces DLLImport() with LibraryImport(). 


Official documentation here - 
Use custom marshallers in source-generated P/Invokes | Microsoft Learn

Sampe Pseudo Code

// Import user32.dll (containing the function we need) and define
// the method corresponding to the native function.

[DllImport("user32.dll", EntryPoint = "MessageBoxW", CharSet = CharSet.Unicode, SetLastError = true)]

private static extern int MessageBoxW(IntPtr hWnd, wstring lpText, string lpCaption, uint uType);

//>>>>>>>>>>>> .NET7 New P/Invoke Method <<<<<<<<<<<<
[LibraryImport("user32.dll", EntryPoint = "MessageBoxW", SetLastError =true,
StringMarshalling = StringMarshalling.Utf16)]

internal static partial int MessageBoxW(IntPtr hWnd, string lpText, string lpCaption, uint uType);

Differences from DllImport

LibraryImportAttribute is intended to be a straightforward conversion from DllImportAttribute in most cases, but there are some intentional changes:

There are also differences in support for some settings on MarshalAsAttribute, default marshalling of certain types, and other interop-related attributes. For more details, see our documentation on compatibility differences.

.NET CONF 2022 Video Release



No comments:

Post a Comment