一、使用vs2017生成c动态库
1、 文件->新建->项目

2、 visual C++ -> Windows桌面 -> Windows桌面向导,并修改下边文件名和路径

应用程序类型选择:动态链接库(.dll) 勾选空项目

3.添加c文件 在《源文件》右键选择 添加->新建项

4选择c++文件(.cpp) ,下边的文件名改成dll_test.c,注意是.c后缀 点击添加

5.添加头文件 《头文件》右键选择 添加->新建项

选择头文件并更改文件名 dll_test.h 点击添加

6,在c文件中红添加测试代码。注意一定要包含刚在自己建的头文件,因为里边有导出的语句
#include <stdio.h>
#include "dll_test.h" //刚才新建的头文件一定要包含
int add(int a, int b)
{
return a + b;
}
在.h文件中添加代码
#ifndef _DLL_TEST_
#define _DLL_TEST_
#pragma once
__declspec(dllexport) int add(int a, int b);
#endif
7.将项目改成x64的编译环境,和unity环境对应

8.生成->生成解决方案 就会看到生成的dll了

二、unity3d使用dll库
1、unity新建个工程

2、随便添加个物体 GameObject->3D Object->Cube

3、添加脚本 ,并将脚本拖拽到物体上


将生成的dll拖拽到Assets处,也可以建个文件夹放进去

4编辑main文件添加测试代码([DllImport("c_dll")] 导入dll库)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class main : MonoBehaviour {
[DllImport("c_dll")]
private static extern int add(int a, int b);
// Use this for initialization
int a = add(3, 5);
void Start () {
print("a+b= " + a);
}
// Update is called once per frame
void Update () {
}
}
4、运行查看输出程序正常运行

