P/Invoke Fundamentals
Declare and call native functions using DllImport, understand marshaling primitives, strings, and structs.
What Is P/Invoke?
Platform Invocation Services (P/Invoke) lets C# call functions in native shared libraries (.dll on Windows, .so on Linux, .dylib on macOS). It is the standard mechanism for calling Win32 APIs or any C-ABI library from .NET.
Your First P/Invoke Call
Declare the native function with [DllImport] and give the library name. The CLR handles finding and loading the library and marshalling arguments.
using System.Runtime.InteropServices;
// Calling MessageBoxW from user32.dll (Windows)
internal static partial class NativeMethods
{
[DllImport("user32.dll",
EntryPoint = "MessageBoxW",
CharSet = CharSet.Unicode,
SetLastError = true)]
internal static extern int MessageBox(
IntPtr hwnd,
string text,
string caption,
uint type);
}
// Call it:
NativeMethods.MessageBox(IntPtr.Zero, "Hello!", "P/Invoke", 0);
// Windows-only — wrap in RuntimeInformation.IsOSPlatform check
// for cross-platform code