[英]Call Objective-C from Go with UTF-8 string
我正在嘗試從 Go 調用一個 Objective-C 函數; 這工作得很好,但我的問題出現在 UTF-8 字符串中。 我不知道如何在 Go 代碼中創建NSString*
,或者如何通過char*
傳遞 UTF-8 字符串。
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)
}
正如預期的那樣,輸出是:
測試漢字測試
測試ʺ¢≠ó測試
誰能幫我這個?
在你的 Objective-C 代碼中,你想要:
void printUTF8(const char * iconPath) {
// NSLog(@"%s", iconPath);
NSLog(@"%@", @(iconPath)); // "test 漢字 test"
}
使用裝箱表達式@(iconPath)
確保創建一個有效的 NSString。 例如,如果傳遞了錯誤的UTF-8
序列(例如嘗試"Fr\\xe9d\\xe9ric" ),它將安全地呈現為null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.