Unity3D 调用C++的DLL的代码

时间:2021-02-27 19:02:57

我使用的是 vs2012生成的DLL

1使用vs创建一个 名为 TestDll 的 Win32控制台应用程序

Unity3D 调用C++的DLL的代码

, 应用程序类型选择: DLL, 附加类型选择:空项目.

Unity3D 调用C++的DLL的代码

2添加TestDll.h, TestDll.cpp文件,并生成 TestDll.dll文件

Unity3D 调用C++的DLL的代码

TestDll.h

#ifndef _TEST_DLL_H_
#define _TEST_DLL_H_
#endif

#if defined (EXPORTBUILD)
# define _DLLExport __declspec (dllexport)
# else
# define _DLLExport __declspec (dllimport)
#endif

extern "C" int _DLLExport add( int x, int y );

_DLLExport class TestDll
{
public:
TestDll(void);
~TestDll(void);


};

TestDll.cpp

#define EXPORTBUILD

#include "TestDll.h"


int add(int x, int y )
{
return x + y;
}

TestDll::TestDll(void)
{
}


TestDll::~TestDll(void)
{
}


生成DLL

Unity3D 调用C++的DLL的代码

3把生成的TestDll拖到Unity的Asset-->Plugins目录(没有就创造一个)

Unity3D 调用C++的DLL的代码

4新建一个UnityTestDll C#文件

UnityTestDll.cs

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class UnityTestDll : MonoBehaviour {

[DllImport("TestDll")]
private static extern int add( int x, int y );

int i = add( 5, 7 );

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

void OnGUI()
{
GUI.Button( new Rect( 1, 1, 200, 100 ), "this dll i = 5+7, i is" + i );
}
}

5运行Unity显示结果

Unity3D 调用C++的DLL的代码