Home > Software design >  Call Objective-C from Go with UTF-8 string
Call Objective-C from Go with UTF-8 string

Time:11-01

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?

CodePudding user response:

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.

  • Related