为了账号安全,请及时绑定邮箱和手机立即绑定

使用 UTF-8 字符串从 Go 调用 Objective-C

使用 UTF-8 字符串从 Go 调用 Objective-C

Go
Qyouu 2022-10-10 18:01:40
我正在尝试从 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)}正如预期的那样,输出是:测试汉字测试测试 ʺ¢Â≠ó 测试谁能帮我这个?
查看完整描述

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.


查看完整回答
反对 回复 2022-10-10
  • 1 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信