.NET 与非托管代码交互:System.Runtime.InteropServices 命名空间详解
在 .NET 开发中,与非托管代码进行交互是一项常见的需求。 System.Runtime.InteropServices
命名空间提供了一系列的类型和工具,帮助开发者实现与非托管代码的互操作性。本文将详细介绍该命名空间中的部分重要类型及其使用方法。
1. UnmanagedMarshal
UnmanagedMarshal
类位于 System.Reflection.Emit
命名空间( mscorlib.dll
),它定义了在调用非托管代码时,参数或字段应如何进行封送处理。默认情况下,CLR 在封送过程中会自动应用某些格式转换,例如将 System.String
对象转换为非托管的 BSTR
。可以使用该类来覆盖默认行为。
创建 UnmanagedMarshal
实例,可使用以下静态方法之一来定义所需的非托管类型:
public sealed class UnmanagedMarshal {
// Public Instance Properties
public field UnmanagedType BaseType{get; }
public field int ElementCount{get; }
public field UnmanagedT