简体   繁体   中英

Searching Serial Ports with IOKit - Swift

I'm trying to understand IOKit and how it allows me to access serial ports in a Swift program.

The class I'm manipulating at the moment is as follows:

import Foundation

import Cocoa

import IOKit.serial.IOSerialKeys



class Serial {

    init() {
    }

    @IBOutlet var serialListPullDown : NSPopUpButton!

    func refreshSerialList(defaultprompt: String) {


        // remove everything from the pull down list
        serialListPullDown?.removeAllItems()

        // ask for all the serial ports
        IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(kIOSerialBSDServiceValue), io_iterator_t)

    }
}

Based on what I've read I think I've setup IOServiceMatchingServices correctly but I'm getting several errors such as "Expected member name or constructor call after type name" and "'o_iterator_t.Type' is not convertible to 'UnsafeMutualPointer'"

What does this mean?

A few different issues going on in there -- let's get your imports squared away first. It looks like you need these two:

import IOKit
import IOKit.serial

For the parameters, it'll be easier to see what we're working with if we define them as local variables, like so:

// this one's easy, just grabbing a constant from IOKit.serial
let masterPort: mach_port_t = kIOMasterPortDefault
// here we get back an Unmanaged<CFMutableDictionary> and need to convert it to
// a CFDictionary using takeRetainedValue()
let classesToMatch: CFDictionary = IOServiceMatching(kIOSerialBSDServiceValue).takeRetainedValue()
// the iterator that will contain the results of IOServiceGetMatchingServices
var matchingServices: io_iterator_t = 0

And lastly, you call the method:

// note that the last parameter is an UnsafeMutablePointer<io_iterator_t>
// so we need to prefix matchingServices with an ampersand (&)
let kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, &matchingServices)
if kernResult == KERN_SUCCESS {
    // success
} else {
    // error
}

This feels pretty near the edge of what Swift can handle right now -- definitely read these two pages well before going further:

Lastly, make sure you can get into the converted Swift declarations for the IOKit framework. There are a lot of useful comments and you'll be able to see which parameters and return values are unmanaged or pointers (since I don't think this framework's official documentation has been updated yet).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM