Table of Contents
Microsoft .NET P/Invoke (Platform Invoke)
Return to dot NET, Foreign Function Interface (FFI)
P/Invoke (Platform Invoke) is a technology in the .NET framework that enables managed code (written in languages like C# or VB.NET) to call unmanaged functions implemented in native libraries, typically written in C or C++. It provides a way to bridge the gap between the managed and unmanaged worlds, allowing .NET applications to access functionality not natively available within the .NET framework.
Key Features
- **Calling Native Functions:** P/Invoke allows .NET code to invoke functions implemented in DLLs (Dynamic Link Libraries) or other native libraries.
- **Data Marshalling:** It handles the conversion of data types between the managed and unmanaged environments, ensuring correct interpretation and passing of parameters.
- **Error Handling:** P/Invoke provides mechanisms for error handling and exception management when interacting with native code.
- **Function Pointers:** It supports the use of function pointers, allowing for greater flexibility in calling native functions.
Resources
Code Example
```csharp using System.Runtime.InteropServices;
class Example {
// Declare the native function [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
static void Main() { // Call the native function MessageBox(IntPtr.Zero, "Hello from P/Invoke!", "Message", 0); }} ```
In this example, `DllImport` attribute specifies the DLL name (`user32.dll`) and character set (`CharSet.Unicode`). The `MessageBox` function is declared with its parameters and return type. The `Main` method calls the `MessageBox` function to display a message box.