UnsafePointer< Uint8>的问题在Swift的SQLite项目中 [英] Issue with UnsafePointer<Uint8> in SQLite project in Swift
问题描述
我们正在使用Swift在iOS中实现SQLite,而不使用包装器或Objective-C桥接。一切正常,除了在进行查询和提取结果时。问题在于从Swite中的SQLite返回的 UnsafePointer< UInt8>
,如下所示:
We are implementing SQLite in iOS, in Swift, without using wrappers or Objective-C bridging. Everything works fine, except when doing a query and extracting the result. The issue is with the UnsafePointer<UInt8>
that is returned from SQLite in Swift as follows:
var querySQL = "SELECT address, phone FROM CONTACTS WHERE NAME = 'myName'"
var cQuery = querySQL.cStringUsingEncoding(NSUTF8StringEncoding)
var statement: COpaquePointer = nil
if sqlite3_prepare_v2(contactsDB, cQuery!, -1, &statement, nil) == SQLITE_OK {
if sqlite3_step(statement) == SQLITE_ROW {
var address : UnsafePointer<UInt8> = sqlite3_column_text(statement, 0)
var data = NSData(bytes: address, length: 10)
var string = NSString(data: data, encoding: NSUTF8StringEncoding)
println(string)
正如您所看到的,如果我们知道对象的长度,我们可以将指针转换为String(在这个案例10)
As you can see, we can convert the pointer to String if we know the length of the object (in this case 10)
为了深入研究这个问题,我有以下例子
To dig into this issue, I have the following example
let pointerFromString: UnsafePointer<Int8> = "xyz".cStringUsingEncoding(NSUTF8StringEncoding)
let stringFromPointer = String.fromCString(anotherPointerFromString_Int8) println(stringFromPointer!)
鉴于 CChar
是 Int8
的别名,我可以转换 String
to UnsafePointer< Int8>
使用 .cStringUsingEncoding()
,然后返回 String
使用 .fromCString(< UnsafePointer_CChar>)
Given that CChar
is an alias of Int8
, I can convert a String
to UnsafePointer<Int8>
using .cStringUsingEncoding()
, and then back to String
using .fromCString(<UnsafePointer_CChar>)
问题是我的SQLite结果是 UnsafePointer_UInt8
,它不能用于 .fromCString()
The problem is that my SQLite result is a UnsafePointer_UInt8
, that can´t be used with .fromCString()
底线问题是:是否可以将 UnsafePointer_UInt8
转换或转换为 UnsafePointer_Int8
The bottom line question is: Is it possible to convert or cast a UnsafePointer_UInt8
to UnsafePointer_Int8
推荐答案
这应该有效:
let address = sqlite3_column_text(statement, 0)
let string = String.fromCString(UnsafePointer<CChar>(address))
Swift 3更新(Xcode 8),比较 Swift 3:转换以null结尾的UnsafePointer< UINT8>到字符串:
let string = String(cString: sqlite3_column_text(statement, 0))
这篇关于UnsafePointer< Uint8>的问题在Swift的SQLite项目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!