前言
Unity3D是一款非常優秀的遊戲引擎,可以使用C#作爲腳本語言進行編程。但是有的時候我們需要運行一些第三方的程序,例如C++實現的一些算法。我們需要將C++的代碼以DLL的形式嵌入到Unity3D的程序中。這時候就要用到C#調用C++ DLL的方法。本文給出一個最簡單的調用方式,實現了一些簡單數據類型的傳遞。
1 C++中DLL的生成
在Windows平臺上,首先使用VisualStudio2013來創建一個C++的Win32控制檯應用程序。工程名設置爲TestDLL。
在應用程序設置嚮導中,選擇應用程序類型爲DLL。
由於我們使用的Unity3D分32位和64位,所以我們需要在配置管理器中設置與Unity一致的位數。我的Unity3D是64位的,所以我做了如下設置。
然後將下面的代碼粘貼到TestDll.cpp中。
#include "stdafx.h"
extern "C"_declspec(dllexport) void fun0(int &a)
{
a = 111;
}
extern "C"_declspec(dllexport) void fun1(int *b)
{
*b = 222;
}
extern "C"_declspec(dllexport) void fun2(int c[])
{
c[0] = 333;
}
extern "C"_declspec(dllexport) void fun3(char *d)
{
*d = 'B';
}
然後點擊生成解決方案,就可以在“工程根目錄\x64\Release”路徑下看到生成的TestDll.dll。
2 在Unity3D中調用C++的DLL
創建一個新工程和一個新場景,並創建一個腳本UseDll.cs。腳本的內容如下:
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class UseDll : MonoBehaviour {
[DllImport("TestDll")]
private static extern void fun0(ref int a);
[DllImport("TestDll")]
private static extern void fun1(ref int b);
[DllImport("TestDll")]
private static extern void fun2(int[] c);
[DllImport("TestDll")]
private static extern void fun3(ref char d);
void Start () {
//初始化a、b、c、d 幾個數據
int a = 0;
int b = 0;
int[] c=new int[5];
for(int i=0;i<5;i++)
{
c[i] = -1;
}
char d = 'A';
//調用dll中的函數,對數據進行修改
fun0(ref a);
Debug.Log(a);
fun1(ref b);
Debug.Log(b);
fun2(c);
Debug.Log(c[0]);
fun3( ref d);
Debug.Log(d);
}
void Update () {
}
}
將這個腳本綁定到攝像機上,並且要把上一步中生成的TestDll.dll拷貝一份放到“Unity工程根目錄\Assets\Plugins”目錄下。默認的時候Assets下是沒有Plugins文件夾的,需要自己創建。一切就緒後,可以運行程序,在控制檯顯示如下信息,表示C#中初始化的數據已經在C++的DLL中被修改,即C#成功調用了C++的DLL。