我正在尝试使用 Swift调用DADiskMountWithArguments 。
swiftfunc DADiskMountWithArguments(_ disk: DADisk, _ path: CFURL?, _ options: DADiskMountOptions, _ callback: DADiskMountCallback?, _ context: UnsafeMutableRawPointer?, _ arguments: UnsafeMutablePointer<Unmanaged<CFString>>!)
我的问题是从 Swift 字符串数组到UnsafeMutablePointer<Unmanaged<CFString>>!这是预期的参数输入格式。
从文档:
arguments
要传递给 /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 上。而且我还没有找到将参数数组放入内存并获得正确指针的方法。
我尝试过的事情:
- 尝试使用 CFArrayGetValues:
// 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 吗?
- 尝试在没有 CFArrayGetValues 的情况下创建 c 字符串数组 (char **)。但我真的不知道我会怎么做呢?
// 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)
还是不透明指针是桥接不同类型的关键,还是我看错了?
任何帮助是极大的赞赏!
谢谢你。