如何将 const void *bytes 从 Swift 传递到 Objective-C 块

How to pass const void *bytes to an Objective-C block from Swift

我正在编写一些调用 Objective-C 库的 Swift (1.2) 代码(转录一些早期的 Objective-C 代码)。目前尚不清楚它应该如何工作。我尝试了很多变体,但没有一个能满足编译器的要求。这是我开始使用的 Objective-C 代码:

// Objective-C

NSData *fileData = //

const void *bytes = fileData.bytes;
unsigned int bufferSize = 1024; //Arbitrary

[object writeDataWithBlock:
 ^BOOL(BOOL(^writeData)(const void *bytes, unsigned int length), NSError**(actionError)) {
     for (NSUInteger offset = 0; offset <= fileData.length; offset += bufferSize) {
         unsigned int size = (unsigned int)MIN(fileData.length - i, bufferSize);
         writeData(&bytes[i], size);
     }

     return YES;
 }];

到目前为止,我已经了解了这个 Swift 代码:

// Swift

let fileData = //

let ptr = UnsafePointer<UInt8>(fileData.bytes)
let bufferSize = 1024 // Arbitrary

object.writeDataWithBlock() { (writeData, actionError) -> Bool in
    for var offset = 0; offset <= fileData.length; offset += bufferSize {
        let size = CUnsignedInt(min(fileData.length - offset, bufferSize))
        writeData(UnsafePointer<Void>(ptr[offset]), size)
    }

    return true
}

这给了我这个错误:

Cannot find an initializer for type 'UnsafePointer' that accepts an arguments list of type '(UInt8)'

当我删除 UnsafePointer<Void> 转换以进行更直接的翻译时,产生了这一行:

writeData(&ptr[offset], size)

我得到这个错误,指向 & 字符:

Type of expression is ambiguous without more context

没有 &,它会产生一个 UInt8,给我这个错误:

Cannot invoke 'writeData' with an argument list of type '(Uint8, UInt32)'

我需要做什么才能按顺序从 NSData 中读取字节并将它们传递给另一个方法?

指针算法应该(并且确实)能为您提供所需的结果。

let fileData = //
let bufferSize = 1024 // Arbitrary

object.writeDataWithBlock() { (writeData, actionError) -> Bool in
    for var offset = 0; offset <= fileData.length; offset += bufferSize {
        let size = CUnsignedInt(min(fileData.length - offset, bufferSize))
        writeData(fileData.bytes + offset, size)
    }

    return true
}