我正在嘗試從 Go 調(diào)用一個(gè) Objective-C 函數(shù);這很好用,但我的問題出現(xiàn)在 UTF-8 字符串上。我不知道如何NSString*在 Go 代碼中創(chuàng)建一個(gè),或者如何通過char*.package main/*#cgo CFLAGS: -x objective-c#cgo LDFLAGS: -framework Cocoa#import <Cocoa/Cocoa.h>void printUTF8(const char * iconPath) { NSLog(@"%s", iconPath);}*/import "C"import ( "fmt" "unsafe")func main() { goString := "test 漢字 test\n" fmt.Print(goString) cString := C.CString(goString) defer C.free(unsafe.Pointer(cString)) C.printUTF8(cString)}正如預(yù)期的那樣,輸出是:測試漢字測試測試 êo¢?≠ó 測試誰能幫我這個(gè)?
1 回答

梵蒂岡之花
TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
在您的 Objective-C 代碼中,您需要:
void printUTF8(const char * iconPath) {
// NSLog(@"%s", iconPath);
NSLog(@"%@", @(iconPath)); // "test 漢字 test"
}
使用裝箱表達(dá)式@(iconPath)可確保創(chuàng)建有效的 NSString。例如,如果UTF-8傳遞了錯(cuò)誤的序列(例如嘗試"Fr\xe9d\xe9ric"),它將安全地渲染到null.
- 1 回答
- 0 關(guān)注
- 86 瀏覽
添加回答
舉報(bào)
0/150
提交
取消