1

I'm trying to pass the bytes contained within a Data? to a C function. The C function is declared like:

void func(const void *buffer);

And my Swift looks like:

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

However, this results in an error:

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

If I change UnsafeRawPointer to UnsafePointer<Void>, then the code builds, but I get a warning:

UnsafePointer<Void> has been replaced by UnsafeRawPointer

What is the right way to fix this?

craig65535
  • 3,439
  • 1
  • 23
  • 49

1 Answers1

3

Since you can pass any data pointer to a C function taking a void * argument, the problem can be solved with

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

Alternatively you can just omit the type annotation and let the compiler infer the type automatically:

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

or

myData?.withUnsafeBytes {
    myfunc($0)
}

Interestingly, the type is inferred as UnsafePointer<Void>, without any warning.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382