step 1:在VS2017中新建项目,Visual C++ ->Windows桌面->Windows桌面向导,命名为DLL_test。点击确定后,应用程序类型选择”动态链接库(.dll)","空项目"。
创建头文件“dll_test.h”
#define Dll_API _declspec(dllexport) //定义宏,后接准备封装的函数
extern "C" Dll_API int _stdcall add(int a, int b);// 使用C语言进行编译,封装使用的函数
其中,extern "C"是实现C和C++的混合编程,告诉编译器这部分代码按C语言的格式进行编译,而不是C++。DLL声明导出函数格式为:
extern "c" XXXAPI 函数返回值 _stdcall 函数名(参数);其中 如果产生的dll只给C/C++程序使用,就没必要定义为_stdcall调用方式;如果要给win32汇编(或其他以此类型调用的程序),则使用_stdcall。
创建源文件“dll_test.cpp”
#include <stdio.h>
#include <iostream>
#include "dll_test.h" //刚才新建的头文件一定要包含
using namespace std;
Dll_API int _stdcall add(int a, int b)
{
return a + b;
}
设置为x64的形式;右键点击项目->属性->C/C++->高级->编译为 C++ 代码(/TP);点击生成->生成解决方案,在输出中可以看到dll生成的位置。
step 2:在Unity中调用生成的.dll
创建Unity项目,在Assets中新建文件夹Plugins,将生成的dll_1.dll拖入该文件夹下。
新建GameObject->Camera,为其添加脚本testDLL.cs:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public class testDLL: MonoBehaviour {
[DllImport("dll_1", EntryPoint = "add")]
static extern int add(int a, int b);
int i = add(4, 9);
// Use this for initialization
void Start () {
}
void OnGUI()
{
GUI.Button(new Rect(10,10,200,100),"测试Dll i=4+9, i is '"+i+"'");
}
// Update is called once per frame
void Update () {
}
}
点击运行