-1
即時嘗試在使用FSEvent Api的mac中測試簡單的filewatcher。 我得到的事件回調,似乎一切正常,但我無法恢復在上下文結構的信息字段中包含的信息。這裏是我的代碼:在FSEventStreamCreate回調中丟失上下文指針(C++)
void feCallback(ConstFSEventStreamRef streamRef,
void* pClientCallBackInfo,
size_t numEvents,
void* pEventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[]);
Watcher::Watcher(const QString& pathToFolder) :
folderPath_(pathToFolder)
{
CFStringCreateWithCString(kCFAllocatorDefault,path,kCFStringEncodingUTF8);
NSString *directory = [[NSString stringWithUTF8String:folderPath_.toStdString().c_str()] stringByDeletingLastPathComponent];
NSArray *pathToWatch = [NSArray arrayWithObjects:directory, nil];
FSEventStreamContext context = {0, (void*)this, NULL, NULL, NULL}; //the second parameter is the 'user info' field
CFAbsoluteTime latency = 3.0;
FSEventStreamRef stream;
stream = FSEventStreamCreate(NULL,
&feCallback,
&context,
(CFArrayRef)pathsToWatch,
kFSEventStreamEventIdSinceNow,
latency,
kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer);
if (!stream)
{
qDebug() << "Could not create event stream for path";
return;
}
else
{
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
FSEventStreamStart(stream);
qDebug() << "stream created";
}
}
QString Watcher::getFolderPath()
{
return folderPath_;
}
void feCallback(ConstFSEventStreamRef streamRef,
void* pClientCallBackInfo,
size_t numEvents,
void* pEventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
Q_UNUSED(streamRef)
Q_UNUSED(eventIds)
qDebug() << ((Watcher*)pClientCallBackInfo)->getFolderPath();
}
我在回調中得到一個sigsev錯誤。此外,如果我的背景下,只插入一個int,例如:
int testInt = 4;
FSEventStreamContext context = {0, &testInt, NULL, NULL, NULL};
在回調
qDebug() << *((int*)pClientCallBackInfo);
打印我-1
那麼,我究竟做錯了什麼? Thx提前!
嘗試在創建事件流時記錄'this'的指針值,然後嘗試記錄'pClientCallBackInfo'的指針值。我懷疑它是通過很好,但你的問題是,該對象或其''folderPath_'成員不再有效。在使用'testInt'進行測試時,問題在於變量在堆棧中。一旦構造函數返回,該空間將被重用於其他內容,並且地址引用垃圾(在某些情況下恰好等於-1)。 (順便說一句,'Watcher'和'MacWatcher'有什麼區別?) –
Macwatcher是一個錯字,thx指出了它。 – Cits
你說得對,問題出在'看守'的對象,創造,而不是指針。 Thx再次。 – Cits