Native DLLs
การเรียกใช้งาน DLL
P/Invoke ย่อมาจาก Platform Invocation Services ทำหน้าที่อนุญาติให้สามารถเข้าถึงเมธอดต่างๆ ใน Unmanaged DLL
เช่นการสร้างเมธอดเพื่อแสดง MessageBox ซึ่งในการสร้างเมธอดนี้จะต้องทีการประกาศ attribute ที่ชื่อ DllImport ด้วย ดังนี้
[DllImport("user32.dll")] และจะต้องมีการ using System.Runtime.InteropServices; ด้วย
ตัวอย่าง เปิด Console Application ขึ้นมา
พิมพ์โค้ดดังนี้
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
class Program
{
[DllImport("user32.dll")]
static extern int MessageBox(IntPtr hwnd, string text, string caption, int type);
public static void Main()
{
MessageBox(IntPtr.Zero, "How are you?", "Welcome", 0);
}
}
}
ผลลัพธ์จะได้ดังรูป

ถ้าต้องการ เรียกใช้ LoadString ก็สามารถเขียนได้ดังนี้
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
class Program
{
[DllImport("User32.dll")]
static extern int LoadString(IntPtr hInstance, int uID, StringBuilder lpBuffer, int nBufferMax);
public static void Main()
{
StringBuilder sb = new StringBuilder();
int i = LoadString(IntPtr.Zero, 111, sb, 255);
string s = i.ToString();
Console.WriteLine(s);
Console.ReadLine();
}
}
}
ถ้าต้องการให้ struct สามารถที่จะเข้าถึง unmanaged method
เช่นถ้าต้องการ เรียกใช้เมธอด GetSystemTime ก็สามารถเขียนได้ดังนี้
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
[StructLayout(LayoutKind.Sequential)]
class Test
{
public long year;
}
class Program
{
[DllImport("kernel32.dll")]
static extern void GetSystemTime(Test test);
public static void Main()
{
Test t = new Test();
GetSystemTime(t);
Console.WriteLine(t.year);
Console.ReadLine();
}
}
}
การกำหนด CharSet(CharSet)
CharSet ทำหน้าทีกำหนดรูปแบบการเข้ารหัสตัวอักษร มี 4 แบบด้วนกันคือ Ansi,Auto,None,Unicode
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
class Program
{
[DllImport("user32.dll",CharSet=CharSet.Ansi)]
public static extern int MessageBox(int hWnd,string text,string caption,int type);
public static void Main()
{
MessageBox(0,"hello","Test",2);
}
}
}
ผลลัพธ์แสดงดังรูป

การแสดงข้อความออกมาโดยใช้
msvcrt.dll
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
class Program
{
[DllImport("msvcrt.dll")]
public static extern int puts(string str);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
static void Main()
{
puts("Hello");
}
}
}
ผลลัพธ์จะแสดง Hello ออกมา
[With great power comes great responsibility]