How to call C from Swift?

前端 未结 6 1601
夕颜
夕颜 2020-11-27 10:33

Is there a way to call C routines from Swift?

A lot of iOS / Apple libraries are C only and I\'d still like to be able to call those.

For example, I\'d like

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 10:48

    It appears to be a rather different ball 'o wax when dealing with pointers. Here's what I have so far for calling the C POSIX read system call:

    enum FileReadableStreamError : Error {
    case failedOnRead
    }
    
    // Some help from: http://stackoverflow.com/questions/38983277/how-to-get-bytes-out-of-an-unsafemutablerawpointer
    // and https://gist.github.com/kirsteins/6d6e96380db677169831
    override func readBytes(size:UInt32) throws -> [UInt8]? {
        guard let unsafeMutableRawPointer = malloc(Int(size)) else {
            return nil
        }
    
        let numberBytesRead = read(fd, unsafeMutableRawPointer, Int(size))
    
        if numberBytesRead < 0 {
            free(unsafeMutableRawPointer)
            throw FileReadableStreamError.failedOnRead
        }
    
        if numberBytesRead == 0 {
            free(unsafeMutableRawPointer)
            return nil
        }
    
        let unsafeBufferPointer = UnsafeBufferPointer(start: unsafeMutableRawPointer.assumingMemoryBound(to: UInt8.self), count: numberBytesRead)
    
        let results = Array(unsafeBufferPointer)
        free(unsafeMutableRawPointer)
    
        return results
    }
    

提交回复
热议问题