unity中调用dll文件总结
根据收集的资料,对unity中调用dll文件进行总结,目前常用的两种,在给出vs中封装dll文件的步骤。
一、调用c#中的dll文件
1.1封装dll文件
首先新建一个项目
然后创建一个类库,例如命名为Csharp
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Csharp { public class Class1 { public static string getName(string name) { return name; } } }
然后编译成dll文件,名字为Csharp.dll
1.2.在unity中使用自定义的dll组件
在unity中创建一个Plugins文件夹,所有的外部引用的dll组件必须要放在这个文件下,才能被using。如果是C#封装的dll,就用 using的方式引用,如果是C++的dll,就DllImport[""]的方式来添加对dll的引用。然后我在C#脚本中用这个dll
using UnityEngine; using System.Collections; using Csharp; //引用c#生成的dll文件,namespace的名字 public class TestDllOne : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void OnGUI() { if (GUILayout.Button("test c# dll")) { Debug.Log(Class1.getName("hello world ")); } }
二、调用c++中的dll文件
在本文中用VS2013进行 C++创建DLL图解
1.创建项目: Win32->Win32项目,名称:MyDll
.
单击下一步后选择如下图所示
单击完成后,右击选择头文件-->添加 ----> 新建项如下图操作
选择头文件并且命名,例如TestDll.h,命名后单击添加
在TestDll.h 头文件中写入代码如下
# define _DLLExport __declspec (dllexport) # else # define _DLLExport __declspec (dllimport) #endif extern "C" int _DLLExport MyADD(int x, int y);
选择源文件,如下图所示
选择添加后,在Test.cpp 源文件中写入代码如下
//宏定义 #define EXPORTBUILD //加载头文件 #include "TestDll.h" //设置函数 int _DLLExport MyADD(int x, int y) { return x + y; }
编译后将生成的MyDll.dll 文件导入unity中的Plugins文件中
如果是C++的dll,就DllImport[""]的方式来添加对dll的引用
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; //调用c++中dll文件需要引入 public class TestDllOne : MonoBehaviour { [DllImport("MyDll")] static extern int MyADD(int x , int y); // Use this for initialization void Start () { } // Update is called once per frame void OnGUI() { if (GUILayout.Button("test c++ dll")) { int i = MyADD(12 , 23); Debug.Log("sum = :" + i.ToString()); } } }
第一次写博客,如有不足,请指正。