我正在嘗試從 Go 調用一個 Objective-C 函數;這很好用,但我的問題出現在 UTF-8 字符串上。我不知道如何NSString*在 Go 代碼中創建一個,或者如何通過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)}正如預期的那樣,輸出是:測試漢字測試測試 êo¢?≠ó 測試誰能幫我這個?
1 回答

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