Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Unmanaged code trong C#

Unmanaged code: Code không chạy dưới quản lý của CLR (Common Language Runtime).

Đặc điểm

  • Không được GC quản lý bộ nhớ
  • Không có type safety, exception handling của .NET
  • Truy cập trực tiếp memory qua con trỏ (pointer)
  • C/C++ code, COM, Win32 API, device drivers

Unsafe code trong C#

C# cho phép unsafe context để dùng pointer:

static unsafe void Main(string[] args)
{
    int var = 20;
    int* p = &var; // Address-of
    
    Console.WriteLine("Data: {0}", var);
    Console.WriteLine("Address: {0}", (int)p);
    Console.ReadKey();
}

Yêu cầu compile: Project Properties -> Build -> Allow unsafe code (/unsafe flag).

Interop với Unmanaged Code

  • P/Invoke: [DllImport("kernel32.dll")] gọi Win32 API
  • COM Interop: Tương tác COM object
  • C++/CLI: Bridge managed/unmanaged
  • UnmanagedCallersOnly: Callback từ native

Marshalling

Chuyển đổi dữ liệu giữa managed/unmanaged: Marshal class, struct layout ([StructLayout(LayoutKind.Sequential)]), IntPtr cho handle/pointer.