Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Swift array into CFArray?

I'm trying to capture a window list in a Mac OS X app using Swift. The CGWindowListCreateImageFromArray function requires a CFArray. I've tried several things and this is the closest I've got. Or is there a better way to convert the array?

import Cocoa

// Example swift array of CGWindowID's
var windowIDs = [CGWindowID]();
windowIDs.append(1);
windowIDs.append(2);

// Convert to CFArray using CFArrayCreate
let allocator = kCFAllocatorDefault
let numValues = windowIDs.count as CFIndex
let callbacks: UnsafePointer<CFArrayCallBacks> = nil
var values: UnsafeMutablePointer<UnsafePointer<Void>> = nil

/* how do I convert windowIDs to UnsafeMutablePointer<UnsafePointer<Void>> for the values? */

let windowIDsCFArray = CFArrayCreate(allocator, values,  numValues, callbacks);

let capture = CGWindowListCreateImageFromArray(CGRectInfinite, windowIDsCFArray, CGWindowImageOption(kCGWindowListOptionOnScreenOnly));
like image 259
iamamused Avatar asked Apr 30 '26 05:04

iamamused


2 Answers

You can initialize your UnsafeMutablePointer with your array so long as you set your CGWindowIDs to CFTypeRef:

var windows: [CFTypeRef] = [1, 2]
var windowsPointer = UnsafeMutablePointer<UnsafePointer<Void>>(windows)
var cfArray = CFArrayCreate(nil, windowsPointer, windows.count, nil)
like image 50
kellanburket Avatar answered May 02 '26 18:05

kellanburket


Converted Ian's answer to Swift 4:

let windows = [CGWindowID(17), CGWindowID(50), CGWindowID(59)]
let pointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: windows.count)
for (index, window) in windows.enumerated() {
    pointer[index] = UnsafeRawPointer(bitPattern: UInt(window))
}
let array: CFArray = CFArrayCreate(kCFAllocatorDefault, pointer, windows.count, nil)

let capture = CGImage(windowListFromArrayScreenBounds: CGRect.infinite, windowArray: array, imageOption: [])!
let image: NSImage = NSImage(cgImage: capture, size: NSSize.zero)

Swift.print(image)
like image 38
Niels Avatar answered May 02 '26 19:05

Niels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!