Unity——在C#中调用C++动态链接库(DLL)

一、创建C++动态链接库(DLL)

1、新建C++空项目

打开VS,新建一个C++空项目,自命名项目名称与位置。

2、配置项目属性为动态链接库

右键项目,点击属性,打开项目属性页,将常规中的配置类型改为动态库(.dll)。

 3、添加.h头文件

右键头文件,点击添加—>新建项,选择头文件.h,命名为DllForUnity.h,点击添加。

代码如下: 

#pragma once
#include<math.h>
#include<string.h>
#include<iostream>
#define _DllExport _declspec(dllexport) //使用宏定义缩写下
 
 
extern "C"
{
   float _DllExport GetDistance(float x1, float y1, float x2, float y2);
}

4、添加.cpp文件

右键源文件,点击添加—>新建项,选择C++文件.cpp,命名为DllForUnity.h,点击添加。

代码如下: 

#include <DllForUnity.h>

float GetDistance(float x1, float y1, float x2, float y2)
{
    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}

5、设置编译为C++代码

右击项目,点击属性,对C/C++下面的高级中的编译为选择“编译为C++代码(/TP)”。

6、生成解决方案

点击生成->生成解决方案,生成之后,会显示出生成成功。

7、确定生成.dll文件

在项目路径下x64文件夹的Debug中就可以看到生成的.dll文件

二、将Dll库在Unity工程中调用

1、创建Unity工程

打开Unity创建新项目,添加两个Cube,分别命名为Cube1、Cube2,添加一个空物体命名为Main。

2、将Dll文件放入Unity项目中

在项目下的Assets文件夹下新建一个文件夹命名为Plugins,将之前生成的动态链接库放到Plugins文件夹下

3、新建脚本调用C++代码

新建Main.cs脚本,并把脚本挂载在Main的空物体下。

代码如下:

using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public class Main : MonoBehaviour
{
    private GameObject cube1;
    private GameObject cube2;
    // Use this for initialization
    void Start()
    {
        cube1 = GameObject.Find("Cube1");
        cube2 = GameObject.Find("Cube2");
        PrintDistanceViaUnity();
    }

    [DllImport("CppAndCS.dll")]
    public static extern float GetDistance(float x1, float y1, float x2, float y2);

    void PrintDistanceViaUnity()
    {
        var pos1 = cube1.transform.position;
        var pos2 = cube2.transform.position;
        Debug.Log("Distance of Two Cube");
        Debug.Log("Distance:" + GetDistance(pos1.x, pos1.y, pos2.x, pos2.y));
    }
}

4、运行结果

控制台输出两个方块的距离,说明成功调用C++的GetDistance方法。

 注:如果Unity已经在运行并且Dll已经存在,那么新的Dll写入生成会失败,此时需要关掉Unity再重新生成。

可能遇到的问题

问题1

问题描述:#include <DllForUnity.h>报错:无法打开源文件。

解决方法:依次点击“项目——配置属性——C/C++——常规”,在“附加包含目录”中加入.h文件所在的文件夹路径。

问题2

问题描述:unity控制台报错: 

 Assets\Main.cs  error CS0246: The type or namespace name 'DllImportAttribute' could not be found (are you missing a using directive or an assembly reference?)

Assets\Main.cs   error CS0246: The type or namespace name 'DllImport' could not be found (are you missing a using directive or an assembly reference?)

 解决方法:

1:一定要 using System.Runtime.InteropServices;

2: [DllImport(“XXXX”)] 需要放在类里面使用

猜你喜欢

转载自blog.csdn.net/weixin_43042683/article/details/130969951
今日推荐