對於非科班出身的程序來說,在沒有學過C和OC的情況,用unity開發iOS相關的功能,是非常痛苦的。簡單寫一下自己遇到的,並且沒有百度到的坑。
1、C#給OC傳遞字典
一般流程是,C#調用C,C調用OC,但是C沒有字典。處理方法,用結構體數組做中轉。核心,結構體數組轉換字典。
C#層代碼
using System.Runtime.InteropServices; using UnityEngine; public class Test : MonoBehaviour { public struct strutDict { public string key; public string value; } [DllImport("__Internal")] private static extern void setNEvent(string eventName, int number, strutDict[] dict); }
OC和C中的代碼
#import <Foundation/Foundation.h> @interface test:NSObject +(test *)instance;@end @implementation test static test *xam = nil; -(id)init{ self = [super init]; if(self){ } return self; } +(test *)instance{ if(xam == nil){ xam = [[test alloc]init]; } return xam; } -(void) testDic:(NSDictionary *)dic { //隨你怎么用 } #if defined(__cplusplus) extern "C"{ #endif struct strutDic{ char* key; char* value; }; void setNEvent (char* eventName, int number,struct strutDic *dict[]){ NSDictionary *nsDic=[[NSDictionary alloc] init]; for(int i=0;i<number;i++){ NSString *key =_CreateNSString((*dict[i]).key); NSString *value =_CreateNSString((*dict[i]).value); [nsDic setValue:value forKey:key]; } [[test instance]testDic:nsDic]; //[reyun setEvent:_CreateNSString(eventName) andExtra:nsDic]; } //char* 轉 nsstring NSString *_CreateNSString(const char* string){ if(string) return [NSString stringWithUTF8String:string]; else return [NSString stringWithUTF8String:""]; } @end