# 原生插件

> Details on using native plug-ins.

Unity 支持原生插件，这些插件是可用 C、C++ 和 Objective-C 等语言编写的原生代码库。插件允许用 C# 编写的代码调用这些库中的函数。此功能允许 Unity 与中间件库或现有的 C/C++ 代码进行集成。

原生插件提供了一个简单的 C 接口，供 C# 脚本后续公开给其他用户脚本。Unity 还可以调用原生插件在发生某些低级渲染事件（例如，创建图形设备时）时导出的函数。请参阅[低级原生插件接口](/engine/6000.0/manual/scripting/compilation-and-code-reload/plug-ins/native-plugin-interface.md)以了解更多信息。

有关原生插件的示例，请参阅[原生渲染器插件](https://github.com/Unity-Technologies/NativeRenderingPlugin)。

## 使用原生插件

要使用原生插件：

1. 使用基于 C 的语言编写函数来访问所需的功能。
2. 将它们编译到库中。
3. 在 Unity 中，创建一个 C# 脚本来调用本机库中的函数。

在目标平台上使用原生代码编译器构建原生插件。由于插件函数使用基于 C 的调用接口，因此必须使用 C 链接来声明函数以避免名称错用问题。

## 示例

具有单个函数的简单本机库可能具有如下所示的代码：

`float ExamplePluginFunction () { return 5.0F; }`

要从 Unity 中访问此代码，请使用如下 C# 代码：

```lang-C#
using UnityEngine;
using System.Runtime.InteropServices;

class ExampleScript : MonoBehaviour {
	#if UNITY_IPHONE
	// On iOS plugins are statically linked into
	// the executable, so we have to use __Internal as the
	// library name.
	[DllImport ("__Internal")]
	#else
	// Other platforms load plugins dynamically, so pass the
	// name of the plugin's dynamic library.
	[DllImport ("PluginName")]   
	#endif
	private static extern float ExamplePluginFunction ();

    void Awake () {
		// Calls the ExamplePluginFunction inside the plugin
		// And prints 5 to the console
		print (ExamplePluginFunction ());
       }
    }
```

## 其他资源

* [低级原生插件接口](/engine/6000.0/manual/scripting/compilation-and-code-reload/plug-ins/native-plugin-interface.md)
* [Mono 互操作性与本机库](https://www.mono-project.com/docs/advanced/pinvoke/)
* [MSDN 上的 P-invoke 文档](https://docs.microsoft.com/en-us/dotnet/framework/interop/marshaling-data-with-platform-invoke?redirectedfrom=MSDN)
