# 适用于低级原生插件的 Memory Manager API

> Access Unity's memory manager and track memory usage from native plug-ins.

`IUnityMemoryManager` 内存管理器 API 是一个 C++ 接口，能在原生插件中使用 Unity 的内存管理和内存性能分析。

借助这个 API，可实现以下操作：

* 通过内存分配器访问 Unity 的内存管理器。
* 通过 Unity 的内存性能分析器包跟踪插件的内存使用情况。

相较于常规的 C++ 内存管理方法，这些功能极大地简化了插件内存分配的管理与分析过程。

插件 API 由在 `IUnityMemoryManager.h` 标头中声明的 IUnityMemoryManager 接口提供。此文件中提供了 API 的完整参考。要查找头文件：

* 在 Windows 上，Unity 将标头存储在 Unity 安装的 `<UnityInstallPath>\Editor\Data\PluginAPI` 文件夹中。
* 在 macOS 上，右键单击 Unity 应用程序，然后选择显示软件包内容 (Show Package Contents) 。标头在 `Contents\PluginAPI` 中。

您应该熟悉以下概念才能有效使用此 API：

* [C++ 指针](https://learn.microsoft.com/en-us/cpp/cpp/pointers-cpp?view=msvc-170)
* [Unity 中的内存](/engine/6000.0/manual/analysis/performance-memory-overview.md)
* [内存性能分析器包](https://docs.unity3d.com/Packages/com.unity.memoryprofiler@latest)
* [内存分配器自定义](/engine/6000.0/manual/analysis/performance-memory-overview/native-allocators/memory-allocator-customization.md)
* [预定义宏](https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=msvc-170)

## 跟踪 Unity 中的内存使用情况

要跟踪插件的内存使用情况，请使用[内存性能分析器包 (Memory Profiler package)](https://docs.unity3d.com/Packages/com.unity.memoryprofiler@latest) 拍摄快照，然后在[全部内存 (All Of Memory) 选项卡](https://docs.unity3d.com/Packages/com.unity.memoryprofiler@latest/index.html?subfolder=/manual/all-memory-tab.html)中打开快照。使用 `IUnityMemoryManager` 分配内存时，内存性能分析器会在创建每个分配器时指定的区域和对象名称下，显示插件的内存分配情况。

以下截屏展示了内存性能分析器包 (Memory Profiler package) 窗口，其中显示了原生插件使用的内存以及使用 `IUnityMemoryManager` API 分配的内存。在此示例中，调用了 **CreateAllocator** 方法，其中“MyNativePlugin”作为 areaName 参数，“MyPluginAllocator”作为 objectName 参数。有关更多信息，请参阅 [CreateAllocator](/engine/6000.0/manual/scripting/compilation-and-code-reload/plug-ins/native-plugin-interface/low-level-native-plugin-memory-manager-api/reference.md#create-allocator)。


**内存性能分析器包 (Memory Profiler package) 窗口中展示了一个名为 Plugin Backend Allocator 的用户自定义分配器的内存使用情况。:**
![](/api/media?file=/engine/6000.0/media/images/native-plugin-memory-snapshot.png)

有关更多信息，请参阅[快照](https://docs.unity3d.com/Packages/com.unity.memoryprofiler@latest/index.html?subfolder=/manual/snapshots.html)。

## 内存管理限制

开发原生插件时，借助这个 API，可运用 Unity 的内存管理系统。虽然这有如上所述的主要优点，但也存在一些限制。Unity 的内存管理系统：

* 不会自动管理；您需要自己分配和取消分配内存。
* 不会被垃圾回收器跟踪和清理。

由于原生 C++ 中的内存没有自动管理支持，因此您需要密切关注应用程序的内存需求。这包括选择正确的内存分配量，并确保在不再需要时取消分配。

`IUnityMemoryManager` API 会对性能产生影响，原因是每次内存分配都要执行一次虚拟调用。为了最大限度降低此性能影响，请使用 API 来减少分配更大内存块的频率。对于较零碎且频繁的内存分配，可先用此 API 分配一个大内存块，然后编写自己的代码来管理这个内存块内的内存。不要使用此 API 进行频繁的小内存分配操作。

## 其他资源

* [原生插件接口](/engine/6000.0/manual/scripting/compilation-and-code-reload/plug-ins/native-plugin-interface.md) - 解释此 API 继承自的基础接口。
* [原生插件](/engine/6000.0/manual/scripting/compilation-and-code-reload/plug-ins/native.md) - 介绍原生插件。
* [内存分配器自定义](/engine/6000.0/manual/analysis/performance-memory-overview/native-allocators/memory-allocator-customization.md) - 说明如何自定义 Unity 的内部内存分配器。
