参考官方教程:Writing Plugins
网上已经有很多类似的了。这里作为自己的笔记,记录如何做一个简单DLL(Dynamic Link Library)动态链接库。
创建使用环境为VS2015。
using UnityEngine;
using System.Runtime.InteropServices; //[DllImport]特性的命名空间。
public class TestScript : MonoBehaviour
{
public int x;
public int y;
#if UNITY_STANDALONE_WIN //WINDOWS系统
const string dll = "MyMaxNumberDLL";
#elif UNITY_STANDALONE_OSX //OSX(Mac)系统
const string dll = "MyMaxNumberBUNDLE";
#elif UNITY_IOS //IOS系统
const string dll = "__Internal";
#else //Android或其他
const string dll = " ";
#endif
[DllImport(dll)]
private static extern int GetMaxNumber(int x, int y);
public static int GetMax(int x,int y)
{
#if (UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_IOS)
return GetMaxNumber(x, y);
#else
return -1;
#endif
}
private void Start()
{
Debug.Log(GetMax(x, y));
}
}
在使用C++的DLL时,出现了一个错误:“Failed to load ‘Assets/Plugins/MyMaxNumberDLL.dll’, expected x64 architecture, but was x86 architecture. You must recompile your plugin for x64 architecture.”在stackoverflow有人回答说需要多导入除了.dll文件的另外4个文件,但无果,又设置了Unity中Build Settings中windows平台的Architecture,但也无果。最后发现原来是C++ DLL编译生成时选择了x86,改成x64重新编译导入就好了。
需要选择x64架构。