How to redirect STDOUT to a NSTextView?

后端 未结 3 807
旧巷少年郎
旧巷少年郎 2021-02-15 14:13

Could anybody show me how to redirect the Stdout to a NSTextView?

and whether the info print by NSLog belong to the std?

Thanks

3条回答
  •  无人共我
    2021-02-15 14:18

    I know the question was about objective-c but I thought I would post a swift answer incase that helps someone else.

    let pipefd = UnsafeMutablePointer.allocate(capacity: 8)
    pipe(pipefd)
    
    dup2(pipefd[1], fileno(stdout))
    
    // Print something here
    
    let buf = UnsafeMutableRawPointer.allocate(byteCount: 1024, alignment: 0)
    read(pipefd[0], buf, 100)
    
    close(pipefd[1])
    
    let output = self.ptrToString(pointer: buf)
    if output != "" {
        // Do something with output
    }
    
    buf.deallocate()
    pipefd.deallocate()
    

    And here is the function I use to convert the pointer to a string:

    func ptrToString (pointer buf: UnsafeMutableRawPointer) -> String {
        let filteredArray = Array(UnsafeBufferPointer(start: buf.assumingMemoryBound(to: UInt8.self), count: 1024)).filter { item in
            return item != 0
        }
    
        return filteredArray
            .map { String(UnicodeScalar(UInt8($0))) }
            .joined()
            .components(separatedBy: "\n")[0]
    }
    

    Works on swift 4

提交回复
热议问题