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代码的方法。