如何调用 sqlite3_open(通过引用传递不透明指针) [英] How to call sqlite3_open (passing opaque pointers by reference)
问题描述
作为练习,我正在尝试为 sqlite3
创建一个包装器.我已经设置了桥接头,并且可以看到 sqlite3
函数的工具提示,但是我不知道如何调用 sqlite3_open
As an exercise, I'm trying to create a wrapper for sqlite3
. I've got the bridging header set up, and I can see the tool tips for the sqlite3
functions, but I can't figure out how to call sqlite3_open
sqlite3.h 包含以下 sqlite3
和 sqlite3_open
的定义:
sqlite3.h contains the following definitions of sqlite3
and sqlite3_open
:
typedef struct sqlite3 sqlite3;
SQLITE_API int sqlite3_open(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);
这意味着 sqlite3_open 将指向匿名结构的指针作为尾随参数,这在工具提示中似乎很清楚:
Which means that sqlite3_open takes as a trailing parameter a pointer to a pointer to an anonymous structure, which seems clear enough in the tooltip:
func sqlite3_open(filename: CString, ppDb: CMutablePointer<COpaquePointer>) -> CInt
知道CMutablePointer的意思是传入&T,我来的最接近的是:
Knowing that CMutablePointer means to pass in &T, the closest I've come is:
class Database {
var handle:COpaquePointer
init(file:String) {
let error = sqlite3_open(file as CString, &handle)
}
deinit {
sqlite3_close(handle)
}
}
sqlite3_close 行没有错误,所以我认为我至少接近了,但是 sqlite3_open 行产生了:
There's no error on the sqlite3_close line, so I think I'm at least close, but the sqlite3_open line yields:
Cannot convert the expression's type 'CInt' to type '$T9'
有关如何执行此操作的任何线索?
Any clues on how to do this?
请不要回答说使用 FMDB 或其他基于 Objective-C 的接口.正如我所说,这至少部分是弄清楚如何从 swift 使用 C 库的练习.
Please, no answers that say to use FMDB or other Objective-C based interfaces. As I said, this is at least partially an exercise in figuring out how to use C libraries from swift.
推荐答案
问题不在于句柄参数,而在于字符串转换.以下作品...
The problem is not with the handle parameter, but with the string conversion. The following works…
class Database {
var handle: COpaquePointer = nil
init(file: NSString) {
let error = sqlite3_open(file.cStringUsingEncoding(NSUTF8StringEncoding), &handle)
}
}
我不确定为什么as CString"不起作用.
I'm unsure as to why the 'as CString' doesn't work.
这篇关于如何调用 sqlite3_open(通过引用传递不透明指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!