近來又把 UC 的 SDK 接到 MonoDevelop(MonoTouch)平台上,過程中遇到不少問題。這裡記錄的是封裝成靜態函式庫的源程式碼。先看用來產生 .a 的工程檔案。

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <pthread.h>
#import "UCGameSdk.h"
#import "UCGameSdkConst.h"
#import "StaticLibraryManager.h"
typedef NSString* (^charge_cb) (NSInteger nType);
typedef struct {
int _roleid;
NSString* _rolename;
NSString* _customInfo;
} product_t;
@interface UseStaticLibraryUc : UIViewController <UCGameSdkProtocol>
// 載入
- (void)viewDidLoad;
- (void)viewDidUnload;
// 登陸部分
- (void)onSdkInitFin: (NSNotification *) notification;
- (void)onLoginFin: (NSNotification *) notification;
- (void)onUnloginExit;
// 支付部分
- (void)onPayFin: (NSNotification *) notification;
- (void)payExit: (NSNotification *) notification;
- (void)buy:(NSInteger)roleId RoleName:(NSString*)roleName customInfo:(NSString*)customInfo;
// 封裝對外接口
+(UseStaticLibraryUc*)Isrance;
-(void)setInitComplete:(charge_cb)complete;
-(void)loginUC:(charge_cb)suc Fail:(charge_cb)fail Cancel:(charge_cb)cancel;
-(void)buyUC:(NSInteger)_roleId RoleName:(NSString*)_roleName customInfo:(NSString*)_customInfo
Success:(charge_cb)suc Fail:(charge_cb)fail Cancel:(charge_cb)cancel;
-(void)setConnectFunc:(charge_cb)sd Rec:(charge_cb)rec Packet:(charge_cb)packet;
-(NSString*)getUserName;
-(NSString*)getUserPasswd;
-(NSString*)getSid;
@end
#import "UseStaticLibraryUc.h"
static charge_cb call_backs[10] = {NULL};
static NSString* game_user = NULL;
static NSString* game_passwd = NULL; // 遊戲帳號登入需要用到的變數
static pthread_cond_t thread_cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t thread_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_t connect_to_our_server = 0;
static NSString* ucsid = NULL;
static NSMutableDictionary *resultDict;
void* wait_for_cour_server_replay(void* arg) {
ucsid = NULL;
while (true) {
if (call_backs[connect_packet] != NULL) {
call_backs[connect_packet](connect_packet);
}
if (call_backs[Connect_receive] != NULL) {
if (call_backs[Connect_receive](Connect_receive) != NULL) {
ucsid = [NSString stringWithFormat:@"%@", call_backs[Connect_receive](Connect_receive)];
if (ucsid == @"error") {
[resultDict setValue:[NSNumber numberWithInt:1] forKey:@"resultCode"];
[resultDict setValue:@"帳號或密碼錯誤,請重新輸入." forKey:@"resultMsg"];
pthread_cond_signal(&thread_cond); // 喚醒阻塞的線程
break;
}
}
}
if (NULL != ucsid) {
int resultCode = 0;
[resultDict setValue:ucsid forKey:@"sid"];
[resultDict setValue:[NSNumber numberWithInt:resultCode] forKey:@"resultCode"];
[resultDict setValue:@"OK" forKey:@"resultMsg"];
pthread_cond_signal(&thread_cond); // 喚醒阻塞的線程
break;
}
}
return NULL;
}
@implementation UseStaticLibraryUc
- (void)viewDidUnload { }
- (void)viewDidLoad { }
// 登入部分
-(id)init {
self = [super init];
if (NULL != self) {
[[NSNotificationCenter defaultCenter] removeObserver:self];
// 添加 Observer 監聽 SDK 初始化事件
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onSdkInitFin:)
name:UCG_SDK_MSG_SDK_INIT_FIN
object:nil];
UCGameSdk *sdk = [UCGameSdk defaultSDK];
// 正式環境參數(由 UC 分配)
// sdk.cpId = 593;
// sdk.gameId = 105539;
// sdk.serverId = 1245;
// 測試環境參數
sdk.cpId = 1;
sdk.gameId = 176;
sdk.serverId = 180;
// YES:聯測模式,SDK 會連到聯測環境;NO:正式生產模式
sdk.isDebug = YES;
sdk.gameUserName = @"叮叮堂官方帳號";
sdk.allowGameUserLogin = YES;
// 設置遊戲附加資訊
ExInfo *exInfo = [[[ExInfo alloc] init] autorelease];
exInfo.cpServiceContact = @"叮叮堂/客服電話:021-50183061";
sdk.exInfo = exInfo;
[sdk initSDK];
NSLog(@"進入到 UC_SDK 的初始化");
}
return self;
}
// SDK 初始化監聽處理函數
- (void)onSdkInitFin: (NSNotification *) notification {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UCG_SDK_MSG_SDK_INIT_FIN
object:nil];
NSDictionary *res = notification.userInfo;
NSNumber *code = (NSNumber *)[res objectForKey:@"code"];
// code 為 1 表示初始化失敗,0 表示成功
if ([code intValue] == 1) {
NSLog(@"監聽到初始化失敗");
return;
}
NSLog(@"監聽到初始化成功");
if (NULL != call_backs[init_complete]) {
call_backs[init_complete](init_complete);
}
[[NSNotificationCenter defaultCenter] removeObserver:self name:UCG_SDK_MSG_LOGIN_FIN object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UCG_SDK_MSG_EXIT_WITHOUT_LOGIN object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLoginFin:)
name:UCG_SDK_MSG_LOGIN_FIN object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUnloginExit)
name:UCG_SDK_MSG_EXIT_WITHOUT_LOGIN object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UCG_SDK_MSG_PAY_FIN object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UCG_SDK_MSG_PAY_EXIT object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPayFin:)
name:UCG_SDK_MSG_PAY_FIN object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payExit:)
name:UCG_SDK_MSG_PAY_EXIT object:nil];
}
// UC 帳號登入
- (void)onLoginFin: (NSNotification *) notification {
NSDictionary *res = notification.userInfo;
NSNumber *code = (NSNumber *)[res objectForKey:@"code"];
// code 為 0 表示登入成功,1 表示失敗
if (code.intValue == 0) {
NSLog(@"成功登入");
if (NULL != call_backs[Login_success]) {
call_backs[Login_success](Login_success);
call_backs[Login_success] = NULL;
}
} else {
NSLog(@"登入失敗");
if (NULL != call_backs[Login_fail]) {
call_backs[Login_fail](Login_fail);
call_backs[Login_fail] = NULL;
}
}
NSLog(@"完成登入處理");
}
// 代表使用者在未登入的情況下退出了登入界面
- (void)onUnloginExit {
NSLog(@"監聽到未登入返回遊戲");
if (NULL != call_backs[Login_fail]) {
call_backs[Login_fail](Login_fail);
call_backs[Login_fail] = NULL;
}
}
- (NSDictionary*)verifyGameUser:(NSString *)gameUser gamePassword:(NSString *)gamePassword {
NSLog(@"線程開始");
pthread_cond_init(&thread_cond, NULL);
pthread_mutex_init(&thread_lock, NULL);
// 發用戶名和密碼給我們的伺服器
pthread_mutex_lock(&thread_lock);
resultDict = [[[NSMutableDictionary alloc] init] autorelease];
game_user = gameUser;
game_passwd = gamePassword;
if (NULL != call_backs[Connect_send]) {
call_backs[Connect_send](Connect_send);
}
pthread_cond_wait(&thread_cond, &thread_lock);
pthread_mutex_unlock(&thread_lock);
pthread_join(connect_to_our_server, NULL);
pthread_mutex_destroy(&thread_lock);
pthread_cond_destroy(&thread_cond);
NSLog(@"string after append is %@", ucsid);
return resultDict;
}
- (void)buy:(NSInteger)_roleId RoleName:(NSString*)_roleName customInfo:(NSString*)_customInfo {
char order[200];
const char *char_content = [_customInfo cStringUsingEncoding:NSASCIIStringEncoding];
sprintf(order, "%s", char_content);
NSString *customInfo = [NSString stringWithUTF8String:order];
NSString *roleId = [NSString stringWithFormat:@"%d", _roleId];
NSString *roleName = _roleName;
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], @"allowContinuousPay",
customInfo, @"customInfo",
roleId, @"roleId",
roleName, @"roleName", nil];
[[UCGameSdk defaultSDK] payWithPaymentInfo:dict];
}
- (void)onPayFin: (NSNotification *) notification {
NSDictionary *res = notification.userInfo;
NSNumber *code = (NSNumber *)[res objectForKey:@"code"];
if (code.intValue == 0) {
if (NULL != call_backs[Buy_success]) {
call_backs[Buy_success](Buy_success);
call_backs[Buy_success] = NULL;
}
} else {
if (NULL != call_backs[Buy_fail]) {
call_backs[Buy_fail](Buy_fail);
call_backs[Buy_fail] = NULL;
}
}
}
- (void)payExit: (NSNotification *) notification { }
#pragma mark - 靜態庫對外接口
static UseStaticLibraryUc *instance = nil;
+(UseStaticLibraryUc*)Isrance {
if (instance == nil) {
instance = [[UseStaticLibraryUc alloc] init];
}
return instance;
}
-(void)setInitComplete:(charge_cb)complete {
call_backs[init_complete] = [complete copy];
}
-(void)loginUC:(charge_cb)suc Fail:(charge_cb)fail Cancel:(charge_cb)cancel {
call_backs[Login_success] = [suc copy];
call_backs[Login_fail] = [fail copy];
call_backs[Login_cancel] = [cancel copy];
NSLog(@"點擊登入按鈕");
[[UCGameSdk defaultSDK] loginWithDelegate:self];
}
-(void)buyUC:(NSInteger)_roleId RoleName:(NSString*)_roleName customInfo:(NSString*)_customInfo
Success:(charge_cb)suc Fail:(charge_cb)fail Cancel:(charge_cb)cancel {
NSLog(@"進入到 buyUC");
call_backs[Buy_success] = [suc copy];
call_backs[Buy_fail] = [fail copy];
call_backs[Buy_cancel] = [cancel copy];
[instance buy:_roleId RoleName:_roleName customInfo:_customInfo];
}
-(void)setConnectFunc:(charge_cb)sd Rec:(charge_cb)rec Packet:(charge_cb)packet {
call_backs[Connect_send] = [sd copy];
call_backs[Connect_receive] = [rec copy];
call_backs[connect_packet] = [packet copy];
}
-(NSString*)getUserName { return game_user; }
-(NSString*)getUserPasswd { return game_passwd; }
-(NSString*)getSid { return [[UCGameSdk defaultSDK] sid]; }
@end
public delegate NSString XMUtilityCallback (int nType);
[BaseType(typeof(UIViewController), Delegates = new string[]{"UCGameSdkProtocol"})]
interface UseStaticLibraryUc {
[Static, Export("Isrance")]
UseStaticLibraryUc Isrance();
[Export("setInitComplete:")]
string setInitComplete(XMUtilityCallback complete);
// 登入
[Export("loginUC:Fail:Cancel:")]
void loginUC(XMUtilityCallback suc, XMUtilityCallback fail, XMUtilityCallback cancel);
[Export("buyUC:RoleName:customInfo:Success:Fail:Cancel:")]
void buyUC(int _roleId, string _roleName, string _customInfo,
XMUtilityCallback suc, XMUtilityCallback fail, XMUtilityCallback cancel);
[Export("setConnectFunc:Rec:Packet:")]
void setConnectFunc(XMUtilityCallback sd, XMUtilityCallback rec, XMUtilityCallback packet);
[Export("getUserName")] string getUserNameUC();
[Export("getUserPasswd")] string getUserPasswdUC();
[Export("getSid")] string getSidUC();
}
當初使用 UC SDK 時,靜態函式庫中的函式會呼叫我們提供的回呼函式。問題是:在那些回呼的實作裡,我們既無法下中斷點,也無法建立執行緒。
查了很久,最後發現是某个 signal 造成的。UC 的技術人員說那是用於錯誤處理的信號,我們請對方把它移除之後,反而就能正常運作。一直沒有明確的答案,加上時間關係,也就沒有再深入探究。
事後回看,這個現象值得記一筆:SDK 若在背景執行緒觸發回呼,Xcode 的除錯器在該執行緒上的行為可能與主執行緒不同;而 pthread_cond_wait 阻塞主執行緒的做法,在 Cocoa 環境中本身就風險極高,容易與執行期的信號處理機制相互干擾。若要在原生與 Mono 之間傳遞非同步結果,用 NSOperationQueue 或 GCD 搭配 delegate 會比自建 pthread 條件變數穩妥得多。