unity调用C++写的dll
·
先写dll


Test.h代码
#pragma once
#if defined (EXPORTBUILD)
# define _DLLExport __declspec (dllexport)
# else
# define _DLLExport __declspec (dllimport)
#endif
extern "C" int _DLLExport MyADD(int x, int y);
Test.cpp代码
//宏定义
#define EXPORTBUILD
//加载头文件
#include "TestDll.h"
//设置函数
int _DLLExport MyADD(int x, int y)
{
return x + y;
}
编译生成dll

拖到unity的Asset下面

写unity端调用的代码TestDllOne.cs如下:

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices; //调用c++中dll文件需要引入
public class TestDllOne : MonoBehaviour
{
[DllImport("Project1")]
static extern int MyADD(int x, int y);
public void Ontestdll()
{
int i = MyADD(12, 23);
Debug.Log("sum = :" + i.ToString());
// Debug.Log($"sum =: {i}");
}
}
代码挂载到button上面即可。运行后 unity的控制台输出log中的计算结果。
全部文件如下:

更多推荐
所有评论(0)