Home
Manage Your Code
Snippet: Pinvoke Example (C#)
Title: Pinvoke Example Language: C#
Description: If you want to call one of the many Win32 API functions that are not available directly from the .NET framework, you should be able to call them using PInvoke (Platform Invoke). (PInvoke is not supported with classes. To call an interface method in a COM Views: 127
Author: Rubin C Date Added: 11/25/2007
Copy Code  
1using System;
2    using System.Runtime.InteropServices;
3
4    namespace TestPInvoke
5    {
6        /// <summary>
7        /// Summary description for Class1.
8        /// </summary>
9        class WrapK32
10        {
11            [DllImport("kernel32.dll")]
12            public static extern bool Beep(int frequency, int duration);
13            /// <summary>
14            /// The main entry point for the application.
15            /// </summary>
16            [STAThread]
17            static void Main(string[] args)
18            {
19                //
20                // TODO: Add code to start application here
21                //
22                Random random = new Random();
23
24                for (int i = 0; i < 10000; i++)
25                {
26                    Beep(random.Next(10000), 100);
27                }
28            }
29        }
30    }
Usage
 How to run unmananaged code as managed code using PInvoke
Notes
The class WrapK32 encapsulates or hides the call to InteropServices. To the user of the Wrap32 class, the Beep function appears as managed code. To invoke the Beep Win32 function, you declare the C# prototype as public static extern as in: public static extern bool Beep(int frequency, int duration); The Beep function is in the kernal32 dll so you tell the runtime using the DllImport attribute directive. [DllImport("kernel32.dll")] public static extern bool Beep(int frequency, int duration);