我正在使用Swift中的包装器使用C的inotify
库。这个想法是提供A Swift软件包管理器库,该库在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 */
};
这里发生了什么?
预先感谢:(
ps:如果您需要更多信息,这是我的完整项目。
name
字段定义为零长度数组:
char name[0]; /* stub for possible name */
那不是进口到斯威夫特。一种可能的解决方案是将偏移计算到在接收缓冲区中的名称字符串开始:
fileSystemEvent = FileSystemEvent(
watchDescriptor: WatchDescriptor(event.wd),
name: String(cString: buffer + currentIndex + MemoryLayout<inotify_event>.size),
mask: event.mask,
cookie: event.cookie,
length: event.len)