Unity supports native plug-ins for Android written in C/C++ and packaged in a shared library (.so) or a static library (.a). When using the IL2CPP scripting backend, you can use C/C++ source files as plug-ins and Unity compiles them along with IL2CPP generated files. This includes all C/C++ source files with extensions .c, .cc, .cpp and .h.
To build a C++ plug-in for Android, use the Android NDK and get yourself familiar with the steps required to build a shared library. The same applies to static libraries.
If you are using C++ to implement the plug-in, you must ensure the methods are declared with C linkage to avoid name mangling issues. By default, only the C source files that have a .c file extension in the plug-ins have C linkage (not C++).
extern "C" {
float Foopluginmethod ();
}
构建库后,将输出的 .so 文件复制到 Unity 项目的 Assets/Plugins/Android 目录中。在 Inspector 中,将 .so 文件标记为与 Android 兼容,并在下拉框中设置所需的 CPU 架构:
要从 C# 脚本调用原生插件中的方法,请使用以下代码:
[DllImport ("pluginName")]
private static extern float Foopluginmethod();
请注意,pluginName 不应包含文件名的前缀(“lib”)和扩展名(“.so”)。建议使用额外的 C# 代码层包装所有的原生插件方法调用。此代码将检查 Application.platform 并仅当应用程序在实际设备上运行时才调用本机方法;在 Editor 中运行时,将从 C# 代码返回虚拟值。请使用平台定义来控制依赖于平台的代码编译。
When you use C/C++ source files as plug-ins, you call them from C# in the same way except that you use __Internal
for plug-in name, for example:
[DllImport ("__Internal")]
private static extern float Foopluginmethod();
The AndroidNativePlugin.unitypackage zip file contains a simple example of a native code plug-in distributed as Unity package.
The sample shows how to invoke C++ code from a Unity application. The package includes a scene which displays the sum of two values as calculated by the native plug-in. To compile the plug-in must install the Android NDK.
To install the sample: