[swift-users] IOKit and USB devices with swift 3

Jérôme Duquennoy jerome+swift at duquennoy.fr
Fri Sep 23 11:46:10 CDT 2016


Hi swift community,

I am trying to access an USB device in a swift project, with quite limited knowledge of IOKit and not a log of experience using unsafe pointers with swift.

My goal is to create a class that will listen to connections and disconnections of a device matching a productID and vendorID.
What I have done up to now is extensively based on that documentation (not swift oriented) :
https://developer.apple.com/library/content/documentation/DeviceDrivers/Conceptual/USBBook/USBDeviceInterfaces/USBDevInterfaces.html#//apple_ref/doc/uid/TP40002645-BBIEIEII <https://developer.apple.com/library/content/documentation/DeviceDrivers/Conceptual/USBBook/USBDeviceInterfaces/USBDevInterfaces.html#//apple_ref/doc/uid/TP40002645-BBIEIEII>
 
The result of my tests and trial can be found here : http://pastebin.com/rSqdFMwH <http://pastebin.com/rSqdFMwH>
(sorry for the pastebin link, but the code is almost 300 lines, which is quite a lot for a mail)

This code compiles on Xcode 8, and the callbacks on plugging and unplugging the device works fine.
But it systematically crashes with an EXC_BAD_ACCESS on the first use of the IOUSBDeviceInterface when a device is detected (on line 143, when trying to open the device).

I guess to have such an error, I must be messing badly with the UnsaveMutablePointer.

Would anyone master IOKit and swift enough to spot my mistake ?
You can test it by executing that  code in a sample project :

try USBDevice(vendorId: 0x04d8, productId: 0xf372)

where vendorId and productId should match one of your connected devices.

Also, there are very few exemples of swift code dealing with IOKit and USB, I would be glad to contribute by publishing that code if I can have it working !

Thanks for your help !

Jerome

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160923/90de6de3/attachment.html>


More information about the swift-users mailing list