44 lines
2.2 KiB
Markdown
44 lines
2.2 KiB
Markdown
#unity/日常积累
|
||
|
||
`Marshal.Copy` 是 .NET 框架中 `System.Runtime.InteropServices.Marshal` 类的一个静态方法,它用于在托管数组和非托管内存块之间复制数据。这个方法在需要与非托管代码交互,比如调用 Windows API 函数或者处理 COM 对象时,特别有用。
|
||
|
||
`Marshal.Copy` 方法有多个重载版本,允许你在不同的数据类型和数组之间复制数据。以下是一些常用的重载:
|
||
|
||
1. **从非托管内存复制到托管数组**:
|
||
|
||
``` cs
|
||
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length);
|
||
```
|
||
|
||
1. - `source`:指向非托管内存块的指针。
|
||
- `destination`:要复制数据到的托管数组。
|
||
- `startIndex`:在托管数组中开始复制数据的索引。
|
||
- `length`:要复制的元素数量。
|
||
2. **从托管数组复制到非托管内存**:
|
||
|
||
``` cs
|
||
public static void Copy(byte[] source, int startIndex, IntPtr destination, int length);
|
||
```
|
||
|
||
1. - `source`:要复制数据的托管数组。
|
||
- `startIndex`:在托管数组中开始复制数据的索引。
|
||
- `destination`:指向非托管内存块的指针。
|
||
- `length`:要复制的元素数量。
|
||
2. **从非托管内存复制到托管数组(自动计算长度)**:
|
||
|
||
``` cs
|
||
public static void Copy(IntPtr source, byte[] destination, int startIndex);
|
||
```
|
||
|
||
1. - 这个重载会根据 `destination` 数组的长度和 `startIndex` 自动计算要复制的元素数量。
|
||
2. **从托管数组复制到非托管内存(自动计算长度)**:
|
||
|
||
``` cs
|
||
public static void Copy(byte[] source, int startIndex, IntPtr destination);
|
||
```
|
||
|
||
1. - 同样,这个重载会根据 `source` 数组的长度和 `startIndex` 自动计算要复制的元素数量。
|
||
|
||
使用 `Marshal.Copy` 时需要注意的是,非托管内存块通常是由非托管代码分配和管理的,因此你需要确保在复制数据后正确地释放或处理这块内存,以避免内存泄漏或其他问题。
|
||
|
||
此外,由于 `Marshal.Copy` 直接与非托管内存交互,因此在使用它时需要特别小心,确保指针和数组索引是有效的,并且不会越界访问内存。 |