我正在嘗試從 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¢≠ó測驗
誰能幫我這個?
uj5u.com熱心網友回復:
在你的 Objective-C 代碼中,你想要:
void printUTF8(const char * iconPath) {
// NSLog(@"%s", iconPath);
NSLog(@"%@", @(iconPath)); // "test 漢字 test"
}
使用裝箱運算式@(iconPath)可確保創建有效的 NSString。例如,如果UTF-8傳遞了錯誤的序列(例如嘗試"Fr\xe9d\xe9ric"),它將安全地呈現為null.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/343425.html
