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.
[DllImport("libc.so.6")] static extern int getpid();
Try it
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.
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
[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
intisint, Clongdiffers between Windows (32-bit) and Linux 64-bit (64-bit),size_tisnuint, pointers areIntPtrornint. - Blittable types (numeric types, pointers, structs of them) are passed without copying;
string,bool,charand arrays need conversion. - Ownership: memory allocated by native code must be freed by the matching native function, not by
Marshal.FreeHGlobalunless that is how it was allocated. Wrap handles inSafeHandle. - Check return values and
GetLastPInvokeError. Native functions signal failure with return codes, not exceptions. - Portability: use
NativeLibraryorDllImportResolverto choose library names per platform. unsafecode and function pointers (delegate* unmanaged<int, int>) give the lowest-overhead calls; see fixed and unsafe.externis 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.