gpt4 book ai didi

macos - 使用 IOKit 搜索串口 - Swift

转载 作者:行者123 更新时间:2023-11-28 05:34:19 25 4
gpt4 key购买 nike

我正在尝试了解 IOKit 以及它如何允许我访问 Swift 程序中的串行端口。

我现在正在操作的类如下:

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)

}
}

根据我读过的内容,我认为我已经正确设置了 IOServiceMatchingServices,但我遇到了几个错误,例如“类型名称后预期的成员名称或构造函数调用”和“'o_iterator_t.Type' 不可转换为 '不安全的相互指针'"

这是什么意思?

最佳答案

其中存在一些不同的问题——让我们先解决您的进口问题。看起来你需要这两个:

import IOKit
import IOKit.serial

对于参数,如果我们将它们定义为局部变量,将更容易看到我们正在处理的内容,如下所示:

// 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

最后,您调用方法:

// 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
}

这感觉非常接近 Swift 现在可以处理的边缘——在继续之前一定要仔细阅读这两页:

最后,确保您可以进入转换后的 IOKit 框架的 Swift 声明。有很多有用的评论,您将能够看到哪些参数和返回值是非托管的或指针的(因为我认为该框架的官方文档尚未更新)。

关于macos - 使用 IOKit 搜索串口 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25320213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com