7. Platform Invoke .net specific
Platform Invoke in .NET
P/Invoke lets managed .NET code call exported functions in unmanaged libraries.
Common uses include device integration, operating-system APIs, and legacy native
libraries.
flowchart LR
A[Managed C# Code] -->|calls extern method| B[CLR P/Invoke Layer]
B -->|loads DLL| C[kernel32.dll]
B -->|resolves function| D[Function Entry Point]
A -->|parameters marshaled| E[Unmanaged Memory]
D -->|executes native API| F[VirtualAllocEx / WriteProcessMemory / ...]
F -->|returns result| B
B -->|returns to C#| AP/Invoke (Platform Invocation) is a feature of the .NET runtime that bridges managed C# code with unmanaged libraries (such as kernel32.dll). By declaring static extern methods with the [DllImport] attribute, you can call Windows API functions directly. The CLR loads the specified DLL at runtime, resolves the function entry point, marshals parameters between managed and unmanaged memory, and returns results just like any other C# call.
The same bridge can reach security-sensitive process and memory APIs, so defenders
should evaluate the called function, target process, requested access, and memory
protections rather than treating P/Invoke itself as malicious.
Common pitfalls include mismatched method signatures, incorrect character-set or
calling-convention declarations, improper marshaling of structures and callbacks,
and stale error retrieval. With [DllImport], set SetLastError = true when the
native contract uses GetLastError, then read the error immediately. Current .NET
also supports source-generated [LibraryImport] declarations where its constraints
fit the interop contract.
Reference: .NET native interoperability best practices