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

31 篇文章 1 订阅

前面系列文章讲解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平台。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Data菌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值