Unity中使用Delegate和Native交互
来源:互联网 发布:英语语法 视频 知乎 编辑:程序博客网 时间:2024/06/06 11:02
Unity中使用Delegate和Native交互
Unity调C的代码是这样的
[DllImport(libName,CallingConvention = CallingConvention.Cdecl)]public static extern int TestCallback (int doit);
那么C要如何调Unity的代码呢?这时Delegate就派上用场,其实我们知道delegate其实就是函数指针,我们将delegate以参数传入C代码,然后在C代码当中调delegate。
public struct CallStruct{ public int handle; [MarshalAs(UnmanagedType.ByValArray,SizeConst=6)] public float[] axes;}public delegate int CallbackeDelegate(int what,int msg,ref CallStruct callStruct);private const string libName = "FBOPlugin";[DllImport(libName,CallingConvention = CallingConvention.Cdecl)]public static extern int TestCallback (int doit,CallbackeDelegate cfunction);
以上代码是在Unity里调TestCallback方法时将CallbackDelegate委托传到Native层,然后在Native层调用这个委托。
例如:
public class MainMethod : MonoBehaviour { public Text mText; // Use this for initialization void Start () { NativeMethod.TestCallback (52, OnFunction); } int OnFunction(int what,int msg,ref NativeMethod.CallStruct callStruct) { mText.text = what + "," + msg+"["+callStruct.handle+","+callStruct.axes[0]+","+callStruct.axes[1]+","+callStruct.axes[2]+","+callStruct.axes[3]+ ","+callStruct.axes[4]+","+callStruct.axes[5]+"]"; return 7; } // Update is called once per frame void Update () { }}
代码中的OnFunction就是CallbackDelegate委托,我们看见在Start的时候调了TestCallback 函数,并将OnFunction方法传递到C代码当中。然后在某个时候C的代码会调OnFunction方法。这样就是实现了C代码调Unity代码。
我来看C++部分;
typedef struct _CallStruct{ int handle; float axes[6];} CallStruct;extern "C"{ typedef int (* Callback)(int wath,int msg,CallStruct& call); UNITY_INTERFACE_EXPORT int UNITY_INTERFACE_API TestCallback(int doit,Callback cfunction);}int TestCallback(int doit,Callback cfunction){ CallStruct strt; strt.handle = 5000; strt.axes[0] = 1; strt.axes[1] = 2; strt.axes[2] = 3; strt.axes[3] = 4; strt.axes[4] = 5; strt.axes[5] = 6; int returenValue = cfunction(doit,666,strt); LOGD("returenValue:%d",returenValue); return returenValue;}
我们看见在C部分的TestCallback的申明和Unity不一样,在Unity当中它的第二个参数是Delegate类型,而在C当中它是函数指针类型。从而更加认证委托就是函数指针。
然后这个函数指针是在TestCallback的实现代码中被调用,当然也可以在其他地方调。
so,我们就实现了C代码调Unity代码的方法。
阅读全文
0 0
- Unity中使用Delegate和Native交互
- 使用Activity和Delegate与Adapter交互
- 使用Activity和Delegate与适配器交互
- React-Native 开发中ScrollView的使用和交互
- Unity中SendMessage和Delegate效率比较
- Unity中SendMessage和Delegate效率比较
- html和native使用JSBridge交互
- 25.Native和Html5的交互(在anroid中使用html5,实现UI交互和数据显示)
- React native和native交互
- 关于unity 使用delegate 和 event 小例子
- Unity AndroidStudio和Unity交互
- Lua和Unity交互
- Unity和Android交互
- Unity在Android和iOS中如何调用Native API
- 关于mono dll和native dll在unity使用
- unity中使用射线碰撞来触发AR中的交互
- unity中使用射线碰撞来触发AR中的交互
- native 和 H5 的交互
- Tomcat 性能调优
- eclipse从svn检索项目工程后的图标说明
- 如何在Word中插入数学公式?
- 乱码整理
- 【上海·签约】中企动力助上海新芳国际物流布局互联网云平台
- Unity中使用Delegate和Native交互
- 微信小程序的坑之编译后界面不改变也不报错
- 一步步开发一个Web服务器.Part 1.
- 第五周学习
- 【OpenGL】多边形的镂空
- 二叉排序树的旋转平衡
- js关闭当前页面(窗口)的几种方式总结(原文:http://www.jb51.net/article/34502.htm)
- HDU 4165 Pills【卡特兰数】
- 极乐技术周报(第十六期)