In this example, the program receives a string from the user and displays it inside a message box. The program uses the MessageBox method imported from the User32.dll library.
|
//using System.Runtime.InteropServices;
class ExternTest
{
[DllImport("User32.dll", CharSet=CharSet.Unicode)]
public static extern int MessageBox(int h, string m, string c, int type);
static int Main()
{
string myString;
Console.Write("Enter your message: ");
myString = Console.ReadLine();
return MessageBox(0, myString, "My Message Box", 0);
}
}
|
This example creates a DLL from a C program that is invoked from within the C# program in the next example.
|
// cmdll.c
// Compile with: /LD
int __declspec(dllexport) SampleMethod(int i)
{
return i*10;
}
|
This example uses two files, CM.cs and Cmdll.c, to demonstrate extern. The C file is the external DLL created in Example 2 that is invoked from within the C# program.
|
// cm.cs
using System;
using System.Runtime.InteropServices;
public class MainClass
{
[DllImport("Cmdll.dll")]
public static extern int SampleMethod(int x);
static void Main()
{
Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5));
}
}
|
|
SampleMethod() returns 50.
|