craig65535
craig65535

Reputation: 3581

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

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?

Upvotes: 1

Views: 947

Answers (1)

Martin R
Martin R

Reputation: 540105

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.

Upvotes: 3

Related Questions