C++制作Windows版动态链接库dll文件给Unity使用

前面系列文章讲解C++语言的语法及API的使用。本篇文章介绍如何制作dll文件给Unity项目使用。

先介绍制作dll文件的过程:

1)创建动态链接库C++工程项目

 

2)删除模板工程脚本文件

 

 3)创建测试脚本文件

 创建头文件MathDll.h

#if 1
# define _DLLExport __declspec (dllexport) //定义该函数的dll
# else  
# define _DLLExport __declspec (dllimport)  //使用该函数
#endif  

//代表c风格的
extern "C"  int _DLLExport Add(int x, int y);

extern "C"  int _DLLExport Max(int x, int y);

 创建实现文件MathDll.cpp

#include <stdio.h>//引入C的库函数
#include "MathDll.h"

//宏定义  
#define  EXPORTBUILD 

//相加
int _DLLExport Add(int x, int y)
{
	return x + y;
}

//取较大的值
int _DLLExport Max(int x, int y)
{
	return (x >= y) ? x : y;
}

4)项目属性配置

 

5)生成dll文件

 

下半部分介绍如何在Unity中导入使用dll文件

1)导入到Unity的Assets/Plugins文件夹下

 2)新建测试脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.Runtime.InteropServices;

public class DllTest : MonoBehaviour {

    [DllImport("Math")]
    private static extern int Add(int x, int y);
    [DllImport("Math")]
    private static extern int Max(int x, int y);


    // Use this for initialization
    void Start()
    {

        int c = Add(3, 7);
        Debug.Log("c = " + c);

        int max = Max(7, 12);
        Debug.Log("max = " + max);
    }

    // Update is called once per frame
    void Update()
    {

    }
}

 点击运行结果如下:

 说明C#代码调用dll文件的C++函数成功!注意:dll文件使用于Unity项目的Windows平台。

Guess you like

Origin blog.csdn.net/hppyw/article/details/119533108