To call a naïve function (outside the .NET Framework), such as MessageBoxA, use the DllImportAttribute attribute like this example:
[DllImport(“user32.dll”)]
To use this function in our C# program, do the following:
1) Declare the function as a C# method by using the two modifiers extern and static:
static extern int MessageBox(int h, string m, string c, int type);
2) Add the attribute DllImport right before the declaration:
[DllImport(“user32.dll”)]
static extern int MessageBoxA(int h, string m, string c, int type);
This attribute tells the program that the required function exists in the library user32.dll.
3) Add the following directive to our program:
using System.Runtime.InteropServices;
Example shows the complete program, which results in a message box titled “My Message Box” that contains the phrase “Hello, World!”
//Example 7-7.cs
//Calling native functions
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
[method: DllImport(“user32.dll”)]
static extern int MessageBoxA(int h, string m, string c, int type);
static ing Main()
{
return MessageBoxA(0, “Hello, World!”, “My Message Box”, 0);
}
}
Wednesday, March 24, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment