gpt4 book ai didi

objective-c - CFReadStreamSetClient 回调函数 - 如何为 C 回调函数提供对包含类的引用?

转载 作者:太空宇宙 更新时间:2023-11-04 03:05:48 26 4
gpt4 key购买 nike

我在下面的网络读取流上使用客户端回调函数:

 -(void)connectToServer
{
if([self isServerConfigured])
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)self.serverAddress);
CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host, self.port, &readStream, &writeStream);

CFStreamClientContext myContext = {
0,
self,
(void *(*)(void *info))CFRetain,
(void (*)(void *info))CFRelease,
(CFStringRef (*)(void *info))CFCopyDescription
};

CFOptionFlags registeredEvents = kCFStreamEventHasBytesAvailable |
kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;

if(CFReadStreamSetClient(readStream, registeredEvents, serverCB, &myContext))
{
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
}
if(!CFReadStreamOpen(readStream)){
NSLog(@"Could not open read stream");
}
}
}

我希望这个回调函数能够调用当前对象(self)中的实例函数。 CFReadStreamSetClient 似乎不会允许我更改回调函数签名,因此我不能只将对当前对象的引用传递给我不认为的回调。

这是回调函数:

 void serverCB(CFReadStreamRef stream, CFStreamEventType event, void *myPtr)
{
switch(event) {
case kCFStreamEventHasBytesAvailable:
[self readStreamData:stream];
break;
case kCFStreamEventErrorOccurred:
NSLog(@"A Read Stream Error Has Occurred!");
break;
case kCFStreamEventEndEncountered:
NSLog(@"A Read Stream Event End!");
break;
default:
break;
}
}

ServerCB 不知道在这个上下文中“self”是什么。有人可以指导我如何解决这个问题吗?

谢谢!

最佳答案

myPtr == self 在这种情况下,因为 self 是您为上下文的 info 字段提供的值.然后该字段通过最后一个参数传递给回调。所以:

void serverCB(CFReadStreamRef stream, CFStreamEventType event, void *myPtr) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
{
MyClass *self = [[(MyClass *)myPtr retain] autorelease];

// ...
// ...
// ...

}
[pool drain];
}

(因为这是 Core Foundation 级别,所以不能保证自动释放池就位,所以在自动释放池中包装这些回调中的 Objective-C 很常见,以防万一。)

关于objective-c - CFReadStreamSetClient 回调函数 - 如何为 C 回调函数提供对包含类的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5292905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com