C const void * param from Swift: Data?.withUnsafeBytes and UnsafeRawPointer

C const void * param from Swift: Data?.withUnsafeBytes and UnsafeRawPointer

我正在尝试将 Data? 中包含的字节传递给 C 函数。 C 函数声明如下:

void func(const void *buffer);

我的 Swift 看起来像:

myData?.withUnsafeBytes { (buffer: UnsafeRawPointer) in
    func(buffer)
}

但是,这会导致错误:

Cannot convert value of type '()' to closure result type '_'

如果我将 UnsafeRawPointer 更改为 UnsafePointer<Void>,则会生成代码,但我会收到警告:

UnsafePointer<Void> has been replaced by UnsafeRawPointer

解决这个问题的正确方法是什么?

因为您可以将 any 数据指针传递给采用 void *参数,问题可以用

解决
myData?.withUnsafeBytes { (buffer: UnsafePointer<Int8>)  in
    myfunc(buffer)
}

或者你可以省略类型注释,让 编译器自动推断类型:

myData?.withUnsafeBytes { (buffer)  in
    myfunc(buffer)
}

myData?.withUnsafeBytes {
    myfunc([=12=])
}

有趣的是,类型被推断为UnsafePointer<Void>,没有 任何警告。