Unity调用c++代码

本文介绍如何创建C++动态链接库(DLL),并在C#中通过DllImport调用该DLL中的方法,包括生成随机数、求两数最大值及计算平方等实用功能。

创建一个 c++动态链接库项目:

1.


在项目 后面选择 DLL empty Project 

3.在SourceFiles添加c++ Files(cpp)代码如下

#include "stdafx.h"

#include "stdlib.h"

extern"C"__declspec(dllexport)intRandom(intmin,intmax)

{

returnrand() % (max - min + 1) + min;

}


extern"C"__declspec(dllexport)intMax(inta ,intb)

{

if(a<=b){

returnb;

}else{

returna;

}

}


extern"C"__declspec(dllexport)intSquare(inta)

{

returna * a;

}

所有希望使用DllImport引入C#的C++方法都应该在方法声明中增加__declspec(dllexport)关键字,除非它在.def文件中对这些方法进行显示声明(.def具体看msdn)

4. 编译:生成DLL 文件

5.新建UNITY ASSEST下的 Plugins文件夹把 c++生成的DLL 放进去 。

6 .在c# 调用c++方法

[DllImport("Native4Unity")]

private extern staticintRandom(intmin,intmax);//调用 c++函数

[DllImport("Native4Unity")]

private extern static intMax(inta,intb);

[DllImport("Native4Unity")]

private extern static intSquare(inta);


if(GUILayout.Button("调用C++ Native中的方法", GUILayout.Height (30)))

{

Debug.Log("调用C++ Native中的方法Random(0,10):"+ Random(0, 10));

Debug.Log("调用C++ Native的方法Max(5,10):"+ Max(5, 10));

Debug.Log("调用C++ Native中的方法Square(5):"+ Square(5));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值