英文:
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)
}
正如预期的输出结果:
test 漢字 test
test 漢字 test
有人能帮我解决这个问题吗?
英文:
I'm trying to call an Objective-C function from Go; this works just fine but my problem shows up with UTF-8 strings. I can't figure it out how to create an NSString*
in the Go code, or how to pass a UTF-8 string via 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)
}
And as expected the output is:
>test 漢字 test
>test 漢字 test
Can anyone help me with this?
答案1
得分: 1
在你的Objective-C代码中,你想要:
void printUTF8(const char * iconPath) {
// NSLog(@"%s", iconPath);
NSLog(@"%@", @(iconPath)); // "test 漢字 test"
}
使用@(iconPath)
这个封装表达式可以确保创建一个有效的NSString。例如,如果传递了一个错误的UTF-8序列(例如尝试使用"Fr\xe9d\xe9ric"),它将安全地渲染为null
。
英文:
In your objective-C code, you want:
void printUTF8(const char * iconPath) {
// NSLog(@"%s", iconPath);
NSLog(@"%@", @(iconPath)); // "test 漢字 test"
}
Using the boxed expression @(iconPath)
ensures a valid NSString is created. For example if a bad UTF-8
sequence is passed (e.g. try "Fr\xe9d\xe9ric") it will safely render to null
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论