对于非科班出身的程序来说,在没有学过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