ภาพรวม
Unmanaged code = โค้ดที่ ไม่อยู่ภายใต้การจัดการของ CLR (Common Language Runtime) เช่น C/C++ native code
Unsafe code ใน C# = โค้ดบล็อกที่ใช้ pointer (ตัวชี้) และต้องคอมไพล์ด้วยตัวเลือก /unsafe อนุญาตให้เข้าถึงหน่วยความจำโดยตรง
ตัวอย่าง Unsafe Code
using System;
class UnsafeCode
{
static unsafe void Main()
{
int x = 100;
int* ptr = &x; // pointer to x
Console.WriteLine("Data: {0}", x);
Console.WriteLine("Address: {0}", (int)ptr);
}
}
คำสำคัญ unsafe
unsafemodifier: ใช้กับ method, type, หรือ block- ใน block
unsafe { ... }ใช้ pointer ได้ - Pointer types:
int*,void*,byte*,char*, etc. - Operators:
&(address-of),*(dereference),->(member access)
การคอมไพล์
- CLI:
csc /unsafe Program.cs - Visual Studio: Project Properties → Build → ☑ Allow unsafe code
- .NET Core/.NET 5+: ต้องเพิ่ม
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>ใน .csproj
เมื่อไหร่ควรใช้ Unsafe
- Interop กับ native libraries (P/Invoke)
- Image processing / graphics ต้องการความเร็วสูงสุด
- ทำงานกับ memory-mapped files, hardware
- หลีกเลี่ยง สำหรับ business logic ปกติ - เสี่ยงต่อ memory corruption, security holes, GC issues