Home

PInvoke

Platform Invocation Services (PInvoke) is a .NET runtime feature that enables managed code to call functions exported by unmanaged libraries, such as native Windows API DLLs or cross‑platform shared libraries. It is used to reuse native code or access operating system facilities from managed code.

PInvoke declares a managed method as external and annotates it with DllImport, specifying the library name

Example: static class NativeMethods { [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int MessageBox(IntPtr hWnd, string

Platform differences affect behavior. Windows typically uses .dll libraries; Linux uses .so and macOS uses .dylib.

Limitations and best practices include minimizing marshaling in hot paths, preferring simple data types, and using

and
optional
entry
point.
The
runtime
marshals
data
between
managed
and
unmanaged
representations
and
applies
the
chosen
calling
convention.
Strings,
arrays,
structs,
and
handles
often
require
explicit
marshaling
rules
via
attributes
such
as
MarshalAs
and
StructLayout.
text,
string
caption,
uint
type);
}
Cross‑platform
code
may
need
per‑platform
signatures
or
dynamic
loading
with
NativeLibrary.Load.
It
is
important
to
specify
appropriate
character
sets,
calling
conventions,
and
platform
ABI
to
ensure
correct
operation.
SafeHandle
for
native
resources
to
ensure
deterministic
release.
Signature
or
calling
convention
mismatches
can
crash
a
process.
Use
SetLastError
and
GetLastWin32Error
semantics
when
interoperating
with
APIs
that
report
errors.
Consider
wrapping
native
calls
in
a
managed
abstraction
to
reduce
risk
and
improve
maintainability.