我试图将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
解决此问题的正确方法是什么?
答案 0 :(得分:2)
因为您可以将任何数据指针传递给C函数
void *
参数,问题可以通过
myData?.withUnsafeBytes { (buffer: UnsafePointer<Int8>) in
myfunc(buffer)
}
或者你可以省略类型注释并让它 编译器自动推断类型:
myData?.withUnsafeBytes { (buffer) in
myfunc(buffer)
}
或
myData?.withUnsafeBytes {
myfunc($0)
}
有趣的是,该类型被推断为UnsafePointer<Void>
,没有
任何警告。