我正在使用 C 的 inotify
库,通过 Swift 中的包装器。这个想法是提供一个 Swift Package Manager 库,它在 Linux 中提供基本的文件系统事件支持。
几乎一切正常。除了这里,我似乎无法复制 inotify_event
成员 name
:
let bufferLength = Int(MemoryLayout<inotify_event>.size + NAME_MAX + 1)
let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: bufferLength)
var fileSystemEvent : FileSystemEvent?
var currentIndex: Int = 0
let readLength = read(Int32(self.fileDescriptor), buffer, bufferLength)
while currentIndex < readLength {
var event = withUnsafePointer(to: &buffer[currentIndex]) {
return $0.withMemoryRebound(to: inotify_event.self, capacity: 1) {
return $0.pointee
}
}
if event.len > 0 {
fileSystemEvent = FileSystemEvent(
watchDescriptor: WatchDescriptor(event.wd),
name: "", //String(cString: event.name),
mask: event.mask,
cookie: event.cookie,
length: event.len
)
}
currentIndex += MemoryLayout<inotify_event>.stride + Int(event.len)
}
我想做的事:
name: String(cString: event.name)
,但是然后编译器抛出一个错误:
`value of type 'inotify_event' has no member 'name'`
关于为什么会发生这种情况,或者关于如何访问 name
成员,我找不到任何线索。以下是 inotify.h
中的结构声明:
/*
* struct inotify_event - structure read from the inotify device for each event
*
* When you are watching a directory, you will receive the filename for events
* such as IN_CREATE, IN_DELETE, IN_OPEN, IN_CLOSE, ..., relative to the wd.
*/
struct inotify_event {
__s32 wd; /* watch descriptor */
__u32 mask; /* watch mask */
__u32 cookie; /* cookie to synchronize two events */
__u32 len; /* length (including nulls) of name */
char name[0]; /* stub for possible name */
};
这是怎么回事?
提前致谢:)
附言:here's my full project ,如果您需要更多信息。
最佳答案
name
字段定义为零长度数组:
char name[0]; /* stub for possible name */
那些不是 导入到 Swift 中。一个可能的解决方案是计算偏移量 接收缓冲区中名称字符串的开头:
fileSystemEvent = FileSystemEvent(
watchDescriptor: WatchDescriptor(event.wd),
name: String(cString: buffer + currentIndex + MemoryLayout<inotify_event>.size),
mask: event.mask,
cookie: event.cookie,
length: event.len)
关于将 C 结构实例复制到 Swift 后缺少成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43816692/