Pole štruktúry spätného volania v C ++ je odovzdané do hornej vrstvy Unity
C Callback Structure Array Is Passed Upper Layer Unity
Nedávno som pracoval na unity sdk. Všetky funkcie musia byť zapuzdrené do C # od dolnej časti C ++. Narazil som na problém. Ako C ++ zavolá späť vlastnú štruktúru údajov na vyššiu úroveň jednoty? Jednoduché typy, int, float sú v poriadku.
C ++ kód
//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 # kód
//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() }