基于VS2017将C++、C#封装代码成dll文件,使用Unity进行调用(二)
标题:Unity调用C++封装后的dll文件:
第一步:新建VS工程,选择C++动态链接库文件命名为Dll2:
第二步写代码
①Dll2.cpp:
// Dll2.cpp : 定义 DLL 应用程序的导出函数。
//
#include “stdafx.h”
#include “dll2.h”
#include <stdio.h>
#include
using namespace std;
Dll2_API int _stdcall Add(int a,int b)
{
return a + b;
}
②右击头文件点击添加–>新建项:新建头文件dll2.h:
dll2.h:
#define Dll2_API _declspec(dllexport) //定义宏,后接准备封装的函数
EXTERN_C Dll2_API int _stdcall Add(int a, int b);// 使用C语言进行编译,封装使用的函数
第三步检查相关配置:
① 注意C++的项目设置为X64,Unity只支持64位.
② 注意:
右击Dll2–>属性
将C/C+±–>高级—>编译为:编译为C++代码,确定。
第四步:新建Unity工程,写Unity端代码:
Unity端代码:
/****************************************************
文件:TestCDllTest.cs
作者:Study
邮箱: 2954806512@qq.com
日期:2019/8/2 17:27:33
功能:Unity调用C++封装代码
*****************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public class TestCDllTest : MonoBehaviour
{
//测试封装C++代码在Unity中使用
[DllImport(@“F:\WorkData\Package\Package\UnityWithDll\C++WithDll\Dll2\x64\Debug\Dll2.dll”, EntryPoint = “Add”)]
extern static int Add(int a,int b);
private void Start()
{
int num=Add(1,1);
Debug.Log(num);
}
}
第五步:将Unity端写的代码找个GameObject拖上去,点击运行。上结果:
点击运行,如图所示:
最后我们发现方法成功调用。
好啦,以上就是《基于VS2017将C#、C++封装代码为dll文件,使用Unity进行调用(二)》的博文。 我是Xiaolin@ustc同学,感谢大家的关注与支持!祝学习进步,工作顺利!最近几个月会持续更博,欢迎大家关注。