小编Bri*_*ice的帖子

在Swift 5中将void *参数传递给c函数时,不推荐使用'withUnsafeBytes'警告

我有一个使用外部提供的C库快速解析FIT文件的库。解析函数将a作为参数void * data。为了调用该函数,我使用转换数据data.withUnsafeBytes( { (ptr: UnsafePointer<UInt8>) in ...}以建立c函数的参数,并且可以正常工作。

将Xcode升级到Swift 5之后,我现在收到了已弃用的警告

不建议使用“ withUnsafeBytes”:请withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R改用

我无法解决如何修复代码以删除不推荐使用的警告。代码运行正常,并且没有迅速发出警告4

我试图更改闭包中的参数UnsafeRawBufferPointer而不是UnsafePointer,但这导致调用该函数时出错:Cannot convert 'UnsafeRawBufferPointer' to expected argument type 'UnsafeRawPointer?'

这是一个小的swift文件,用于显示问题:

import Foundation

// Create sample data (Typically would be read from a file
let data = Data(repeating: 1, count: 10)

data.withUnsafeBytes( { (ptr : UnsafePointer<UInt8>) in
    // call the c function with the void* argument
    let value = readFITfile(ptr)
    print( value ) …
Run Code Online (Sandbox Code Playgroud)

c unsafe-pointers swift

3
推荐指数
1
解决办法
1295
查看次数

标签 统计

c ×1

swift ×1

unsafe-pointers ×1