2015-06-18 93 views
-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提前!

+1

尝试在创建事件流时记录'this'的指针值,然后尝试记录'pClientCallBackInfo'的指针值。我怀疑它是通过很好,但你的问题是,该对象或其''folderPath_'成员不再有效。在使用'testInt'进行测试时,问题在于变量在堆栈中。一旦构造函数返回,该空间将被重用于其他内容,并且地址引用垃圾(在某些情况下恰好等于-1)。 (顺便说一句,'Watcher'和'MacWatcher'有什么区别?) –

+0

Macwatcher是一个错字,thx指出了它。 – Cits

+0

你说得对,问题出在'看守'的对象,创造,而不是指针。 Thx再次。 – Cits

回答

0

该问题与此代码无关。指针工作正常,但他的对象丢失了。