LLMpediaThe first transparent, open encyclopedia generated by LLMs

P/Invoke

Generated by GPT-5-mini
Note: This article was automatically generated by a large language model (LLM) from purely parametric knowledge (no retrieval). It may contain inaccuracies or hallucinations. This encyclopedia is part of a research project currently under review.
Article Genealogy
Expansion Funnel Raw 85 → Dedup 0 → NER 0 → Enqueued 0
1. Extracted85
2. After dedup0 (None)
3. After NER0 ()
4. Enqueued0 ()
P/Invoke
NameP/Invoke
OthernamesPlatform Invocation Services
DeveloperMicrosoft
Released2002
Written inC#, Visual Basic .NET
PlatformCommon Language Runtime
GenreInteroperability

P/Invoke

P/Invoke is a mechanism that enables managed applications running on the Common Language Runtime to call unmanaged functions implemented in native libraries such as those provided by Microsoft Windows API, POSIX, or vendor-specific SDKs. It serves as a bridge between languages hosted by the .NET Framework and external libraries written in languages like C (programming language), C++, or Fortran, allowing reuse of existing native code, access to system services, and integration with platform-specific features. P/Invoke is closely associated with technologies and projects such as Mono (software), .NET Core, .NET 5, and tooling from Microsoft Visual Studio.

Overview

P/Invoke originated with the .NET Framework to complement managed interoperability strategies including COM (Component Object Model) interop and hosting APIs. It leverages metadata and attributes defined by the Common Language Infrastructure standards used by implementations like Microsoft .NET, Mono (software), and CoreCLR to describe function signatures, calling conventions, and data layout. P/Invoke is often used alongside platform-specific SDKs such as the Windows SDK, database client libraries from vendors like Oracle Corporation and MySQL AB, graphics APIs like OpenGL and Direct3D, and multimedia frameworks such as FFmpeg.

Usage and Syntax

Developers declare external methods in managed source code using language features in C#, Visual Basic .NET, or other Common Language Infrastructure-compliant languages, annotating them with attributes to specify the target native library and calling convention. Typical attributes reference loaders and runtime services from System.Runtime.InteropServices and may name exports found in DLLs such as those in the Windows API (for example, functions in kernel32.dll or user32.dll). Declarations specify types that map to native equivalents defined by standards like the C (programming language) ABI and platform ABIs such as x86-64, ARM64, or IA-32.

Marshalling and Data Types

Marshalling controls how data types in managed code are converted to native representations and back; it is governed by attributes and by runtime-provided marshallers in assemblies like mscorlib or System.Private.CoreLib. Primitive types often map to C types: managed System.Int32 maps to int (C programming language), System.IntPtr maps to pointer-sized integers defined by architectures such as x86-64 or ARM64, and System.String requires encoding choices such as UTF-8 or UTF-16 influenced by APIs like Unicode (computing) conventions used in Windows API. Complex types such as structures require explicit layouts, often declared with attributes that reference layout kinds used by ECMA-335 and influenced by compilers like Microsoft Visual C++ or GCC. Marshaling of arrays, callbacks, and function pointers involves concepts used by libffi and patterns recognizable in bindings for projects like GTK+ and Qt.

Platform and Runtime Considerations

Behavior depends on the hosting runtime—implementations such as .NET Framework, .NET Core, and Mono (software) provide differences in loader behavior, symbol resolution, and default character encoding. On Windows (operating system), P/Invoke commonly targets DLL exports in libraries like kernel32.dll or advapi32.dll; on Unix-like systems, it targets shared objects (.so) provided by distributions like Debian or Fedora and by standards such as POSIX. Cross-platform toolchains including MSYS2, Cygwin, and native package systems like apt or yum influence which native libraries are available. Platform-specific calling conventions—stdcall, cdecl, fastcall—and differences in structure packing require attention when moving code between x86 (architecture), ARM (microarchitecture), and PowerPC targets.

Security and Reliability

Invoking unmanaged code bypasses many safety guarantees of the Common Language Runtime, introducing risks such as memory corruption, buffer overruns, resource leaks, and elevation-of-privilege vulnerabilities discussed in contexts like CWE and Common Vulnerabilities and Exposures. Best practices cite least-privilege patterns from Microsoft Security Development Lifecycle and mitigation techniques such as input validation, bounds checking, and use of hardened native libraries provided by vendors like Intel or Red Hat. Managed wrappers can enforce invariants and use safe handles modeled after abstractions in System.Runtime.InteropServices.SafeHandle to reduce resource leaks. Tools for analysis include static analyzers from Coverity, runtime profilers in Visual Studio, and sanitizers such as AddressSanitizer.

Examples and Common Patterns

Common uses include calling Win32 API functions for windowing and file I/O, invoking encryption libraries like OpenSSL, using native multimedia codecs such as libavcodec from FFmpeg, or accessing hardware APIs from vendors including NVIDIA and AMD. Typical patterns: defining a managed extern method with attributes from System.Runtime.InteropServices, creating a marshaled structure with explicit layout as recommended by ECMA-335, handling lifetime with SafeHandle or finalizers, and wrapping low-level calls in higher-level abstractions used by frameworks such as ASP.NET Core or Xamarin. Community projects like PInvoke.net and bindings in MonoGame demonstrate common signature translations and idioms.

Alternatives and Interoperability

Alternatives include COM (Component Object Model) interop for component-based systems, embedding interpreters provided by Python (programming language) or Lua (programming language), using native extensions via C++/CLI or SWIG-generated wrappers, and cross-language bridges like gRPC for process-boundary communication. Interop layers in language runtimes such as Java Native Interface and Rust foreign function interface share conceptual similarities, while containerization and IPC with systems like Docker or ZeroMQ offer decoupling strategies that avoid in-process unmanaged calls.

Category:Microsoft .NET