[swift-users] Passing Data to a f(void *) function

Andrew Trick atrick at apple.com
Mon Jul 3 13:20:42 CDT 2017



> On Jun 30, 2017, at 9:14 AM, Joe Groff via swift-users <swift-users at swift.org> wrote:
> 
> 
>> On Jun 30, 2017, at 7:40 AM, Martin R via swift-users <swift-users at swift.org> wrote:
>> 
>> I have a C function 
>> 
>>   void myfunc(const void *ptr);
>> 
>> which is imported to Swift as
>> 
>>   func myfunc(_ ptr: UnsafeRawPointer!)
>> 
>> This compiles and runs without problems:
>> 
>>   let data = Data(bytes: [1, 2, 3, 4])
>>   data.withUnsafeBytes { (ptr) in myfunc(ptr) } // (A)
>> 
>> and the type of `ptr` is inferred as `UnsafePointer<Void>`. But adding an explicit type
>> annotation produces a compiler warning:
>> 
>>   data.withUnsafeBytes { (ptr: UnsafePointer<Void>) in myfunc(ptr) } // (B)
>>   // warning: UnsafePointer<Void> has been replaced by UnsafeRawPointer
>> 
>> which is understandable in the view of "SE-0107 UnsafeRawPointer API".
>> 
>> The "Fix-it" replaces `UnsafePointer<Void>` by `UnsafeRawPointer`, and that does not
>> compile anymore:
>> 
>>   data.withUnsafeBytes { (ptr: UnsafeRawPointer) in myfunc(ptr) } // (C)
>>   // error: cannot convert value of type 'Void' to closure result type '_'
>> 
>> because there is no `withUnsafeBytes()` method taking a `(UnsafeRawPointer)->ResultType`
>> closure.
> 
> This is a bug. The Data API ought to be using UnsafeRawPointer here.
> 
> -Joe

I was going for UnsafeRawBufferPointer. Here’s a prototype from Sept ‘16:
https://github.com/atrick/swift/commit/796b08fa5635a7d61cbb6bf0718178e0ce326e4f

I created a JIRA to track this and related issues: https://bugs.swift.org/browse/SR-5363

-Andy


More information about the swift-users mailing list