2

I'm seeking to better understand how imported C functions like this can be implemented in Swift. This error message is helpful, but I've tried many variations of this as params in the swift function and can't quite get it.

Cannot convert value of type '() -> ()' to expected argument type 'method_handler?' (aka 'Optional<@convention(c) (Optional<UnsafeMutablePointer<msg_data>>, Optional<UnsafePointer>, Optional<UnsafeMutablePointer<Optional<UnsafeMutablePointer>>>, Int32, Optional) -> ()>')

typedef void (*method_handler)(const msg_data_ptr msg, const char *types,
 arg_ptr *argv, int argc, void *user_data);
func handler(args)
{
 for (i, arg) in args.enumerated() {
 print("argument \(i) is: \(arg)")
 }
}

passed in here:

add_handler_new("handler", &handler, nil, 0, 1);
asked Aug 1, 2021 at 15:52

1 Answer 1

1

As the error message says, you have to use @convention(c) in order to define the swift function or closure that is interoperable with other C functions. Try this:

typealias MethodHandler = @convention(c) (
 _ msg_data_ptr : UnsafeMutablePointer<msg_data>?, 
 _ types: UnsafePointer<Int8>?, 
 _ argv : UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?, 
 _ argc: Int32, 
 _ user_data: UnsafeMutablePointer<Int8>?
 ) -> Void
let handler: MethodHandler = { msg_data_ptr, types, argv, argc, user_data in
 ...
}
add_handler_new("handler", handler, nil, 0, 1)
answered Aug 1, 2021 at 16:56

1 Comment

i'm getting a '&' used with non-inout argument of type error - but removing it from &handler fixes it. It wasn't clear how the closure is handled in this case with an imported C function. inout is a new concept for me that i'm not sure applies here anyway

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.