Unity 支持用 C/C ++ 编写并封装在共享库 (.so) 或静态库 (.a) 中的 Android 原生插件。使用 IL2CPP 脚本后端时,可以使用 C/C++ 源文件作为插件,Unity 会将这些文件与 IL2CPP 生成的文件一起编译。这包括扩展名为 .c、.cc、.cpp 和 .h 的所有 C/C++ 源文件。
要构建适用于 Android 的 C++ 插件,请使用 Android NDK 并熟悉构建共享库所需的步骤。静态库也是如此。
如果使用 C++ 来实现该插件,必须确保使用 C 链接来声明方法以免发生名称错用问题。默认情况下,只有插件中具有 .c 文件扩展名的 C 源文件才具有 C 链接(不是 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# 代码返回虚拟值。请使用平台定义来控制依赖于平台的代码编译。
在使用 C/C++ 源文件作为插件时,可以用相同的方式从 C# 调用这些文件,不同之处是插件名称使用 __Internal
,例如:
[DllImport ("__Internal")]
private static extern float Foopluginmethod();
AndroidNativePlugin.unitypackage zip 文件包含一个分发为 Unity 包的原生代码插件的简单示例。
该示例演示如何从 Unity 应用程序调用 C++ 代码。该包中包含的一个场景显示了由原生插件计算的两个值之和。要编译该插件,必须安装 Android NDK。
要安装该示例,请执行以下操作:
1.下载 zip 文件。 2.解压缩 AndroidNativePlugin.unitypackage 文件。 3.打开 Unity Editor。 4.创建一个新的项目。 5.在新项目中,单击 Assets > Import Package > Custom Package。 6.在 Import Package 文件对话框中,导航到解压缩文件的位置,然后选择该文件。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.