Swift generics and CMutableVoidPointer

2019-05-27 12:32发布

问题:

I have the following function at the moment in my generic class

func writeHeader(buffer: CMutableVoidPointer) {

    var headerData = NSData(bytesNoCopy:buffer, length:sizeof(H))
    self.fileHandle.writeData(headerData)
}

But as you see this is not very type safe. I tried this but it does not compile

func writeHeader(buffer: CMutablePointer<H>) {

    var headerData = NSData(bytesNoCopy:buffer, length:sizeof(H))
    self.fileHandle.writeData(headerData)
}

Any idea?

UPDATE

This is part of a generic class as mentioned in the first sentence, sorry next time im more specific.

class DataStore<H> { 
     .....
}

回答1:

This might be what you are looking for:

func writeHeader<H>(buffer: CConstPointer<H>) {

    let headerData = buffer.withUnsafePointer {
       NSData(bytesNoCopy: $0, length: sizeof(H), freeWhenDone: false)
    }
    self.fileHandle.writeData(headerData)
}