tl;dr-“自动参考”仅适用于托管插件。那是一个 .dll 文件,它是用 C# 编写和编译的。非托管插件(dll 使用非 C# 语言编写,非托管且无法自动引用)
编辑:我刚刚注意到有更多隐藏的 cmets,其中之一是 Aybe 提到它适用于托管 DLL。
edit2:如果你想让项目测试一下,我可以上传它。
我想在编辑器中检查时检查托管和非托管 DLL 之间是否存在差异(在 Unity 2019 中进行测试,但我假设 2018 年也是如此)。
我制作了以下两个 DLL。一个在 C#(托管)中,一个在 CPP(非托管)中。我向它添加了一些简单的功能,以确保它不会由空 dll 引起。
托管 C# 插件
using System;
namespace TestDLLManaged
{
public class TestDLLManaged
{
public static float Multiply(int a, float b)
{
return a * b;
}
}
}
将其编译为针对 .Net 3.5 框架的 DLL(unity 2018 及更高版本支持 4.x,但希望安全起见)并将 .dll 文件放在 /Assets/ 文件夹中(显然是 Assets /Plugin 文件夹旨在与 native/unmanaged 插件一起使用,而不是托管)。
非托管/原生 C++ 插件
//header filer
#pragma once
#define TESTDLLMULTIPLY_API __declspec(dllexport)
extern "C"
{
TESTDLLMULTIPLY_API float MultiplyNumbers(int a, float b);
}
//body
#include "TestDLLMultiply.h"
extern "C"
{
float MultiplyNumbers(int a, float b)
{
return a * b;
}
}
还把它编译成一个dll,放在/Assets/Plugin文件夹中。
我在 DLLImportTest.cs 中调用了两个 DLL,并执行了一个简单的计算,以确保两个 DLL 都被实际导入,并且像这样运行
using static TestDLLManaged.TestDLLManaged;
public class DLLImportTest : MonoBehaviour
{
const float pi = 3.1415926535f;
[DllImport("TestDLL", EntryPoint = "MultiplyNumbers")]
public static extern float UnmanagedMultiply(int a, float b);
// Use this for initialization
void Start()
{
UnityEngine.Debug.LogFormat("validating unmanaged, expeceted result = 100: {0}", UnmanagedMultiply(10, 10f));
UnityEngine.Debug.LogFormat("validating managed, expeceted result = 100: {0}", Multiply(10, 10f));
}
}
在编辑器中检查 DLL 时,似乎托管 (C#) 插件确实 有auto reference 的选项,而非托管/本机 (cpp) dll 确实没有 具有该功能。现在我实际上不知道为什么会出现这种情况,因为在文档中找不到它。也许这是一个错误,也许它背后还有另一个原因。稍后我可能会在论坛上发帖要求更多说明。
作为额外的一点,我决定对这两个函数运行一个基准测试,令我惊讶的是,托管 C# 插件实际上比 cpp 插件快。
private void BenchMark()
{
Stopwatch watch1 = new Stopwatch();
watch1.Start();
for (int i = 0; i < 10000000; i++)
{
UnmanagedMultiply(1574, pi);
}
watch1.Stop();
UnityEngine.Debug.LogFormat("Unmanaged multiply took {0} milliseconds", watch1.Elapsed);
Stopwatch watch2 = new Stopwatch();
watch2.Start();
for (int i = 0; i < 10000000; i++)
{
Multiply(1574, pi);
}
watch2.Stop();
UnityEngine.Debug.LogFormat("Managed multiply took {0} milliseconds", watch2.Elapsed);
}
结果:
Unmanaged multiply took 00:00:00.1078501 milliseconds
Managed multiply took 00:00:00.0848208 milliseconds
对于任何希望自己查看差异/实验的人,我已经制作了一个 git-hub repo here,其中包含我上面使用的项目。