首页 > 解决方案 > 将 UnsafeMutableRawPointer 作为函数参数传递

问题描述

当我尝试将 UnsafeMutableRawPointer 作为函数参数传递时,出现以下错误:

A C function pointer can only be formed from a reference to a 'func' or a literal closure

具体来说,这是来自以下代码:

public func sqlite3_bind_text(_ oP: OpaquePointer!, _ first: Int32, _ second: UnsafePointer<Int8>!, _ third: Int32, _ ptrs: ((UnsafeMutableRawPointer?) -> Void)!) -> Int32 {
    SQLite3.sqlite3_bind_text(oP, first, second, third, ptrs)
}

我看过:如何使用实例方法作为函数的回调,该函数只需要 func 或文字闭包,但看不到如何将其应用于我的情况。

如何通过我的函数传递指针?

标签: swift

解决方案


SQLite 是一个纯 C 库,并将SQLite3.sqlite3_bind_text()指向 C 函数的指针作为第五个参数。这样的参数标有@convention(c),并且必须在您的包装函数中复制:

public func sqlite3_bind_text(_ oP: OpaquePointer!, _ first: Int32,
                              _ second: UnsafePointer<Int8>!,
                              _ third: Int32,
                              _ ptrs: (@convention(c) (UnsafeMutableRawPointer?) -> Void)!) -> Int32 {
    SQLite3.sqlite3_bind_text(oP, first, second, third, ptrs)
}

推荐阅读