C ++コールバック構造体配列がUnityの上位層に渡されます



C Callback Structure Array Is Passed Upper Layer Unity



最近、私はUnitysDKに取り組んでいました。すべての関数は、C ++の下部からC#にカプセル化する必要があります。問題が発生しました。 C ++はどのようにしてカスタムデータ構造を上位レベルのユニティにコールバックしますか?単純な型、int、floatは大丈夫です。

C ++コード

//Custom data structure typedef struct PointInfo { float x float y }PointInfo typedef void(__stdcall *OnTouchDownListener)(void *point,int a) OnTouchDownListener onTouchDown extern 'C' { int SetTouchListner(OnTouchDownListener listener) { onTouchDown = listener } int StartCallBack(){ PointInfo p[] = { {3,4}, {33,44}, } onTouchDown((void*)p, 2)//2 represents the number of elements in the array } }

C#コード

//Define the data structure, one-to-one correspondence with c++ [StructLayout(LayoutKind.Sequential,CharSet = CharSet.Unicode)] public struct PointInfo { public float x public float y } //Define the hosting type private delegate void DLLCplusTouchCallBack(IntPtr array, int length) //Declare local callback instance private DLLCplusTouchCallBack TouchDownCallBack //Define native setting callback interface [DllImport('Native-Unity',CallingConvention = CallingConvention.Cdecl,CharSet =CharSet.Ansi)] public static extern int SetTouchListner(Delegate listener) //Test callback function interface [DllImport('Native-Unity')] public static extern int StartCallback() /* The C# layer callback function will call this function to get the real data structure array content get the data from the Intptr where is from c++ dll. */ private static T[] GetNativeArray(IntPtr array, int length) { T[] result = new T[length] int size = Marshal.SizeOf(typeof(T)) if (IntPtr.Size == 4) //32-bit machine { // 32-bit system for (int i = 0 i typeof(T)) array = new IntPtr(array.ToInt32() + size) } } else//64-bit machine { // probably 64-bit system for (int i = 0 i typeof(T)) array = new IntPtr(array.ToInt64() + size) } } return result } /* The upper c# callback function, c++ will eventually call this function touch down callback */ public void DLLCplusCallBackTouchDown(IntPtr array, int length) { Debug.Log('Enter :DLLCplusCallBackTouchDown length = ' + length) if (length >= 10) length = 10 PointInfo[] resultVertices = GetNativeArray(array, length) if (resultVertices != null) { //Get the data here for (int i = 0 i 'point: ' + length + ' x = ' + resultVertices[i].x + ' point y = ' + resultVertices[i].y) } } } void Start () { TouchDownCallBack = DLLCplusCallBackTouchDown SetTouchListner(TouchDownCallBack) StartCallback() }