在 Swift 中使用函数指针回调方法
Using Function pointer callback methods in Swift
我想更好地了解如何在 Swift 中实现像这样的导入 C 函数。此错误消息很有用,但我已尝试将其作为 swift 函数中的参数进行多种变体,但无法完全理解。
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)")
}
}
在这里传递:
add_handler_new("handler", &handler, nil, 0, 1);
如错误消息所述,您必须使用 @convention(c)
才能定义可与其他 C 函数互操作的 swift 函数或闭包。试试这个:
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)
我想更好地了解如何在 Swift 中实现像这样的导入 C 函数。此错误消息很有用,但我已尝试将其作为 swift 函数中的参数进行多种变体,但无法完全理解。
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)")
}
}
在这里传递:
add_handler_new("handler", &handler, nil, 0, 1);
如错误消息所述,您必须使用 @convention(c)
才能定义可与其他 C 函数互操作的 swift 函数或闭包。试试这个:
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)