Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Reflection, Attributes and Metadata

P/Invoke (platform invoke)

Reference for P/Invoke in C#: call native C functions with DllImport or LibraryImport, map types, set calling conventions and handle errors and safety.

Platform Invoke (P/Invoke) lets managed code call functions exported by native libraries: the C runtime, operating-system APIs, or your own C library. You declare the function as static extern with the [DllImport] attribute, and the runtime loads the library on first call, finds the exported name and marshals the arguments between managed and native representations.

Since .NET 7 you can use [LibraryImport] on a static partial method instead. A source generator writes the marshalling code at build time, which is faster and works with Native AOT. This site's runner has no source generators, so the examples below use DllImport.

C#
[DllImport("libc.so.6")]
static extern int getpid();

Try it

C# Calling the C library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# When the import fails

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
[DllImport("lib", EntryPoint = "name", CallingConvention = CallingConvention.Cdecl,
           SetLastError = true, CharSet = CharSet.Unicode)]
static extern ReturnType Function(ParamType p);

[LibraryImport("lib", StringMarshalling = StringMarshalling.Utf8)]
static partial ReturnType Function(string p);
Option Description
Library name File name without path or extension is allowed; the runtime tries platform-specific variants (.dll, .so, .dylib).
EntryPoint The exported name when it differs from your method name.
CallingConvention Cdecl for most C libraries, StdCall for classic Win32. Wrong values corrupt the stack on 32-bit platforms.
SetLastError Saves the OS error so Marshal.GetLastPInvokeError() can read it.
CharSet / StringMarshalling How string becomes char* (ANSI, UTF-8, UTF-16).
DllImportSearchPath Restricts where the library is searched for.

Errors: DllNotFoundException (library not found), EntryPointNotFoundException (symbol not found), MarshalDirectiveException (unsupported marshalling). A wrongly declared signature usually does not throw: it crashes the process or returns garbage.

Usage notes

  • Match sizes exactly. C int is int, C long differs between Windows (32-bit) and Linux 64-bit (64-bit), size_t is nuint, pointers are IntPtr or nint.
  • Blittable types (numeric types, pointers, structs of them) are passed without copying; string, bool, char and arrays need conversion.
  • Ownership: memory allocated by native code must be freed by the matching native function, not by Marshal.FreeHGlobal unless that is how it was allocated. Wrap handles in SafeHandle.
  • Check return values and GetLastPInvokeError. Native functions signal failure with return codes, not exceptions.
  • Portability: use NativeLibrary or DllImportResolver to choose library names per platform.
  • unsafe code and function pointers (delegate* unmanaged<int, int>) give the lowest-overhead calls; see fixed and unsafe.
  • extern is the language keyword that marks the method as implemented elsewhere: see extern.
  • Sandboxes: the runner here is Linux; Windows API examples (user32.dll) will not run.