Unity3d 调用 C++ DLL之 DLL回调Unity3d C++ DLL回调 C 函数

               

上篇   Unity3d 调用C++ DLL (Win平台)  介绍了简单的 Unity3d 调用 C++ DLL的方法,但是这样是不够的,这里再讲下通过函数指针让 C++ DLL中回调 Unity3d 的方式。

转自http://blog.****.net/huutu 星环游戏 http://www.thisisgame.com.cn

创建DLL 以及在 Unity3d 中调用 DLL 中函数在上篇中介绍了。


首先,在C#中是没有函数指针的,我们使用 Delegate 。

转自http://blog.****.net/huutu 星环游戏 http://www.thisisgame.com.cn

我们来创建 DLL

在上篇的工程中修改。


Calculate.h

# define _DLLExport __declspec (dllexport) //标记为导出函数;//定义函数指针;typedef void (__stdcall *CPPCallback)(int tick);extern "C" void _DLLExport SetCallback(CPPCallback callback);extern "C" long long _DLLExport dlltest();

Calculate.cpp

#include "Calculate.h"long long dlltest(){  long long a = 1;  int b = 0;  while(b<1000000000)  {   a=a+b;   b++;  }  return a;}void SetCallback(CPPCallback callback)int tick=1223; callback(tick);}

在DLL中定义函数SetCallback() 来设置回调函数。

转自http://blog.****.net/huutu 星环游戏 http://www.thisisgame.com.cn

在Unity3d 中使用DLL

using UnityEngine;using System.Collections;using System.Runtime.InteropServices;public class NewBehaviourScript : MonoBehaviour { [DllImport ("TestDLL")private static extern long dlltest(); [DllImport ("TestDLL")private static extern void SetCallback(CSCallback callback)public delegate void CSCallback(int tick)static CSCallback callback; // Use this for initialization void Start () {  callback = CSCallbackFuction; } static void CSCallbackFuction(int tick{  Debug.Log ("CSCallbackFuction "+tick.ToString()); }  void OnGUI({  if(GUI.Button(new Rect(100,100,200,200),"Test DLL"))  {   long before=System.DateTime.Now.Ticks;   Debug.Log("dlltest="+ dlltest());   Debug.Log("take "+(System.DateTime.Now.Ticks-before));  }  if(GUI.Button(new Rect(100,300,200,200),"SetCallback"))  {   long before=System.DateTime.Now.Ticks;   SetCallback(callback);   Debug.Log("take "+(System.DateTime.Now.Ticks-before));  }    if(GUI.Button(new Rect(300,300,200,200),"Test Mono"))  {   long before=System.DateTime.Now.Ticks;   Debug.Log("monotest="+ monotest());   Debug.Log("take "+(System.DateTime.Now.Ticks-before));  } } // Update is called once per frame void Update () {  } long monotest({  long a = 1;  int b = 0;  while(b<1000000000)  {   a=a+b;   b++;  }  return a; }}
转自http://blog.****.net/huutu 星环游戏 http://www.thisisgame.com.cn

运行成功

Unity3d 调用 C++ DLL之 DLL回调Unity3d C++ DLL回调 C 函数

转自http://blog.****.net/huutu 星环游戏 http://www.thisisgame.com.cn

示例工程下载:

http://pan.baidu.com/s/1jG499HW


转自http://blog.****.net/huutu 星环游戏 http://www.thisisgame.com.cn


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.****.net/jiangjunshow