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

huangapple go评论83阅读模式
英文:

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 &lt;Cocoa/Cocoa.h&gt;

void printUTF8(const char * iconPath) {
	NSLog(@&quot;%s&quot;, iconPath);
}
*/
import &quot;C&quot;

import (
	&quot;fmt&quot;
	&quot;unsafe&quot;
)

func main() {
	goString := &quot;test 漢字 test\n&quot;
	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(@&quot;%s&quot;, iconPath);
    NSLog(@&quot;%@&quot;, @(iconPath)); // &quot;test 漢字 test&quot;
}

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.

huangapple
  • 本文由 发表于 2021年10月30日 20:35:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/69779673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定