来自Swift的C const void * param:Data?.withUnsafeBytes和UnsafeRawPointer

时间:2017-06-29 20:38:44

标签: c swift unsafe-pointers

我试图将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

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

1 个答案:

答案 0 :(得分:2)

因为您可以将任何数据指针传递给C函数 void *参数,问题可以通过

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

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

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

myData?.withUnsafeBytes {
    myfunc($0)
}

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