如何将const void *字节传递给Swift的Objective-C块

时间:2015-07-29 19:59:49

标签: objective-c swift nsdata

我正在编写一些调用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
}

这给了我这个错误:

  

找不到类型&#39; UnsafePointer&#39;的初始化程序。接受类型&#39;(UInt8)&#39;

的参数列表

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

writeData(&ptr[offset], size)

我收到此错误,指向&字符:

  

如果没有更多的上下文,表达的类型是不明确的

如果没有&,则会产生UInt8,从而产生以下错误:

  

无法调用“writeData&#39;使用类型&#39;(Uint8,UInt32)&#39;

的参数列表

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

1 个答案:

答案 0 :(得分:1)

指针算术应该(并确实)为您提供您正在寻找的结果。

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
}