&#39; UnsafePointer <INT8>&#39;没有会员&#39; toString&#39;

时间:2017-09-01 03:51:50

标签: swift linux gtk

我正在尝试使用SwiftGtk帮助将Gtk绑定到Swift。但是,在为HeaderBar添加类时,我收到错误:

/home/luis/Dropbox/Documentos/Coding/Swift/SwiftGtk/.build/checkouts/SwiftGtk--2571330441700638662/Sources/HeaderBar.swift:15:63: error: value of type 'UnsafePointer<gchar>' (aka 'UnsafePointer<Int8>') has no member 'toString'
        get { return gtk_header_bar_get_title(castedPointer())?.toString() }
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^ ~~~~~~~~
/home/luis/Dropbox/Documentos/Coding/Swift/SwiftGtk/.build/checkouts/SwiftGtk--2571330441700638662/Sources/HeaderBar.swift:20:66: error: value of type 'UnsafePointer<gchar>' (aka 'UnsafePointer<Int8>') has no member 'toString'
        get { return gtk_header_bar_get_subtitle(castedPointer())?.toString() }
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^ ~~~~~~~~
/home/luis/Dropbox/Documentos/Coding/Swift/SwiftGtk/.build/checkouts/SwiftGtk--2571330441700638662/Sources/HeaderBar.swift:41:75: error: value of type 'UnsafePointer<gchar>' (aka 'UnsafePointer<Int8>') has no member 'toString'
        get { return gtk_header_bar_get_decoration_layout(castedPointer())?.toString() }

似乎正在发生的事情是Gtk.HeaderBar get_title()方法返回gchar,这是(我认为)类型UnsafePointer,它没有在代码中正确地转换为字符串:

public var title: String? {
    get { return gtk_header_bar_get_title(castedPointer())?.toString() }
    set { gtk_header_bar_set_title(castedPointer(), newValue) }
}

public var subtitle: String? {
    get { return gtk_header_bar_get_subtitle(castedPointer())?.toString() }
    set { gtk_header_bar_set_subtitle(castedPointer(), newValue) }
}
  • 我应该遵循哪种方法将其转换为String?

1 个答案:

答案 0 :(得分:1)

String获取UnsafePointer<Int8>有多种方法。请参阅https://developer.apple.com/documentation/swift/string上的String文档。这里的复杂性是相同的字符串具有不同的字节序列表示,这取决于所使用的编码。一种方法是使用init(cString:encoding:)。例如,如果您知道UnsafePointer<Int8>变量buf指向的缓冲区被编码为ASCII,则可以得到如下字符串:

let s = String.init(cString: buf, encoding: String.Encoding.ascii)