Unity调用c++代码
2017-02-06 10:45
267 查看
创建一个 c++动态链接库项目:
1.
![](http://upload-images.jianshu.io/upload_images/1310652-75a90e27c8c6efee.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
在项目 后面选择 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));
}
1.
![](http://upload-images.jianshu.io/upload_images/1310652-75a90e27c8c6efee.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
在项目 后面选择 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));
}
相关文章推荐
- 同一程序中混合调用C和C++代码
- 在C#中调用C/C++代码
- C#托管代码与C++非托管代码互相调用
- JNI技术实践(1) Java调用C/C++代码
- 非托管C++代码调用C#编写的dll方法
- 从 Java 代码调用 C/C++ (整理自IBM在线教程)
- 在C#中调用C/C++代码
- C++反汇编代码分析--函数调用
- c++调用python完整代码(开发环境vs2008)
- 同一程序中混合调用C和C++代码
- 如何让python调用C和C++代码
- [总结]非托管C++代码调用C#编写的dll方法
- 如何让python调用C和C++代码
- 用c# 调用并调试c++的代码
- 如何让python调用C和C++代码
- 在C++中调用Ruby代码
- C#托管代码与C++非托管代码互相调用二(C++调用C#代码)
- JNI技术实践(1) Java调用C/C++代码
- C++ 调用C#代码
- python调用C和C++代码