将 UnsafeMutableRawPointer 作为函数参数传递

Posted

技术标签:

【中文标题】将 UnsafeMutableRawPointer 作为函数参数传递【英文标题】:Pass an UnsafeMutableRawPointer as a function parameter 【发布时间】:2020-10-20 19:00:34 【问题描述】:

当我尝试时,我收到以下错误:

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)

我查看过:How to use instance method as callback for function which takes only func or literal closure,但不知道如何将其应用于我的情况。

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

【问题讨论】:

提供SQLite3.sqlite3_bind_text(...)的签名 func sqlite3_bind_text(_: OpaquePointer!, _: Int32, _: UnsafePointer!, _: Int32, _: ((UnsafeMutableRawPointer?) -> Void)!) -> Int32跨度> 您还必须在包装函数的参数声明中添加“@convention(c)”:_ ptrs: (@convention(c) (UnsafeMutableRawPointer?) -&gt; Void)! – 但是定义与 @987654326 签名相同的函数有什么意义@ 并转接电话? 依赖注入,想换出实现 请注意,最后一个参数不是 UnsafeMutableRawPointer 而是指向函数的指针(它接受 UnsafeMutableRawPointer 参数)。 【参考方案1】:

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)

【讨论】:

以上是关于将 UnsafeMutableRawPointer 作为函数参数传递的主要内容,如果未能解决你的问题,请参考以下文章

Xcode 8.1 Swift 3 错误:无法将“String”类型的值转换为预期的参数类型“UnsafeMutableRawPointer”

无法分配类型“UnsafeMutableRawPointer!”的值输入“UIView”

Swift 结构警告“'UnsafeMutableRawPointer' 的初始化导致指针悬空”

收到“UnsafeMutableRawPointer”类型的错误消息没有下标成员

取消引用 UnsafeMutablePointer<UnsafeMutableRawPointer>

NSMutableData 到 UnsafeMutableRawPointer 的字节不更新 mutableData 的值