我正在尝试使用Swift调用DADiskMountWithArguments。
swiftfunc DADiskMountWithArguments(_ disk: DADisk, _ path: CFURL?, _ options: DADiskMountOptions, _ callback: DADiskMountCallback?, _ context: UnsafeMutableRawPointer?, _ arguments: UnsafeMutablePointer<Unmanaged<CFString>>!)
我的问题是从Swift数组字符串到 UnsafeMutablePointer&lt; Unmanaged&lt; CFString&gt;&gt;!这是预期的参数输入格式。
来自文档:
参数
要传递给/ sbin / mount -o的以空值终止的挂载选项列表。
在Objective-C中,我通过创建如下的参数值来完成相同的调用:
NSArray *args = @[
@"rdonly",
@"noowners",
@"nobrowse",
@"-j",
];
CFStringRef *argv = calloc(args.count + 1, sizeof(CFStringRef));
CFArrayGetValues((__bridge CFArrayRef)args, CFRangeMake(0, (CFIndex)args.count), (const void **)argv);
DADiskMountWithArguments((DADiskRef)_disk, (__bridge CFURLRef)url, kDADiskMountOptionDefault, DiskMountCallback, (__bridge void *)(self), (CFStringRef *)argv);
但我还没有成功将此方法移植到Swift。我还没有找到一种方法将参数数组放入内存并获取正确的指针。
我尝试过的事情:
// Example arguments array
let arguments = ["rdonly", "noowners", "nobrowse", "-j"]
// Create an UnsafeMutableRawPointer and allocate the correct string size
let argsUnsafeMutableRawPointer = calloc(arguments.count + 1, MemoryLayout<CFString>.size)
// Convert the Mutable pointer to an Immutable one
let argsUnsafeRawPointer: UnsafeRawPointer? = UnsafeRawPointer.init(argsUnsafeMutableRawPointer)
// CFArrayGetValues expects an UnsafeMutablePointer<UnsafeRawPointer?>. I have an UnsafeRawPointer, but can't get it into an UnsafeMutablePointer<T>.
let argsUnsafeMutablePointer: UnsafeMutablePointer<UnsafeRawPointer?>! = ?
// Call CFArrayGetValues
CFArrayGetValues(arguments as CFArray, CFRangeMake(0, CFIndex(arguments.count)), argsUnsafeMutablePointer)
// Call DADiskMountWithArguments
DADiskMountWithArguments(self.diskRef, url, DADiskMountOptions(kDADiskMountOptionDefault), diskMountCallback, nil, ?)
我应该使用不透明指针从UnsafeRawPointer桥接到UnsafeMutablePointer吗?
// Example arguments array
let arguments = ["rdonly", "noowners", "nobrowse", "-j"]
// Create an Unmanaged<CFString> from the arguments array
let argsUnmanagedCFString: Unmanaged<CFString> = ?
// Create an UnsafeMutablePointer<Unmanaged<CFString>>! from the argsUnmanagedCFString
let argsUnsafeMutablePointer: UnsafeMutablePointer<Unmanaged<CFString>>! = ?
// Call DADiskMountWithArguments
DADiskMountWithArguments(self.diskRef, url, DADiskMountOptions(kDADiskMountOptionDefault), diskMountCallback, nil, argsUnsafeMutablePointer)
是不是不透明的指针是弥合不同类型的关键,或者我是以错误的方式看待这个?
非常感谢任何帮助!
谢谢。