RSCG – System.Runtime.InteropServices
RSCG – System.Runtime.InteropServices
name | System.Runtime.InteropServices |
nuget | https://www.nuget.org/packages/System.Runtime.InteropServices/ |
link | https://learn.microsoft.com/en-us/dotnet/standard/native-interop/pinvoke-source-generation |
author | Microsoft |
Generate PInvoke calls
This is how you can use System.Runtime.InteropServices .
The code that you start with is
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net7.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <PropertyGroup> <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> </Project>
The code that you will use is
WriteLine(MessageBoxW(IntPtr.Zero, "asd", "asd", 1)); //RSCG WriteLine(MessageBoxW_LI(IntPtr.Zero, "asd", "asd", 1));
partial class DemoImport { [DllImport("user32.dll", EntryPoint = "MessageBoxW", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern int MessageBoxW(IntPtr hWnd, string lpText, string lpCaption, uint uType); [LibraryImport("user32.dll", EntryPoint = "MessageBoxW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] internal static partial int MessageBoxW_LI(IntPtr hWnd, string lpText, string lpCaption, uint uType); }
global using static System.Console; global using static DemoImport; global using System.Runtime.InteropServices;
The code that is generated is
// <auto-generated/> unsafe partial class DemoImport { [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Interop.LibraryImportGenerator", "7.0.8.17405")] [System.Runtime.CompilerServices.SkipLocalsInitAttribute] internal static partial int MessageBoxW_LI(nint hWnd, string lpText, string lpCaption, uint uType) { int __lastError; int __retVal; // Pin - Pin data in preparation for calling the P/Invoke. fixed (void* __lpText_native = &global::System.Runtime.InteropServices.Marshalling.Utf16StringMarshaller.GetPinnableReference(lpText)) fixed (void* __lpCaption_native = &global::System.Runtime.InteropServices.Marshalling.Utf16StringMarshaller.GetPinnableReference(lpCaption)) { System.Runtime.InteropServices.Marshal.SetLastSystemError(0); __retVal = __PInvoke(hWnd, (ushort*)__lpText_native, (ushort*)__lpCaption_native, uType); __lastError = System.Runtime.InteropServices.Marshal.GetLastSystemError(); } System.Runtime.InteropServices.Marshal.SetLastPInvokeError(__lastError); return __retVal; // Local P/Invoke [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "MessageBoxW", ExactSpelling = true)] static extern unsafe int __PInvoke(nint hWnd, ushort* lpText, ushort* lpCaption, uint uType); } }
Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/System.Runtime.InteropServices
Leave a Reply