Unity调用C++的dll
2014年09月04日
以windows平台为例
- 创建dll项目
// test.h\
\#if defined (EXPORTBUILD)\
\#define \_DLLExport \_\_declspec (dllexport)\
\#else\
\#define \_DLLExport \_\_declspec (dllimport)\
\#endif\
\
extern "C" int \_DLLExport func();\
\
// test.cpp\
\#define EXPORTBUILD\
\#include "test.h"\
\
int func(){\
return 110;\
}
用release版本编译。
- 在Unity3D的Project视图下创建Plugins目录,将生成的NativeInvoke.dll链接库拷贝到Plugins目录下.
- 在脚本中(以C#为例),写入如下代码即可调用
using UnityEngine;\
using System.Runtime.InteropServices;\
\
class NativeInvoke : MonoBehaviour\
{\
\
\#if UNITY\_IPHONE || UNITY\_XBOX360\
\
// On iOS and Xbox 360 plugins are statically linked into\
// the executable, so we have to use \_\_Internal as the\
// library name.\
[DllImport ("\_\_Internal")]\
\
\#else\
\
// Other platforms load plugins dynamically, so pass the name\
// of the plugin's dynamic library.\
\
/\*\*\
\* @note\
\* the name is "NativeInvoke", but not "NativeInvoke.dll"\
\*/\
[DllImport("NativeInvoke")]\
\
\#endif\
\
private static extern int func();\
\
void Awake()\
{\
// Calls the FooPluginFunction inside the plugin\
// And prints 5 to the console\
print("DLL");\
print(func());\
}\
}