1

When I try to pass an UnsafeMutableRawPointer as a function parameter I get the following error:

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

Specifically this is from the following code:

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)
}

I've looked at: How to use instance method as callback for function which takes only func or literal closure but can't see how I can apply that to my situation.

How can I pass the pointer through my function?

5
  • Provide signature of SQLite3.sqlite3_bind_text(...)
    – Kamil.S
    Oct 20, 2020 at 19:05
  • func sqlite3_bind_text(_: OpaquePointer!, _: Int32, _: UnsafePointer<Int8>!, _: Int32, _: ((UnsafeMutableRawPointer?) -> Void)!) -> Int32 Oct 20, 2020 at 19:07
  • 2
    You have to add “@convention(c)” to the parameter declaration of your wrapper function as well: _ ptrs: (@convention(c) (UnsafeMutableRawPointer?) -> Void)! – But what is the point of defining a function with the same signature as SQLite3.sqlite3_bind_text and forwarding the call?
    – Martin R
    Oct 20, 2020 at 19:09
  • Dependency injection, want to swap out the implementation Oct 20, 2020 at 19:15
  • 1
    Note that the last parameter is not a UnsafeMutableRawPointer but a pointer to a function (which takes a UnsafeMutableRawPointer parameter).
    – Martin R
    Oct 20, 2020 at 19:32

1 Answer 1

1

SQLite is a pure C library, and SQLite3.sqlite3_bind_text() takes a pointer to a C function as the fifth parameter. Such a parameter is marked with @convention(c) and that must be replicated in your wrapper function:

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)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.