简体   繁体   English

将CFSocket上下文转换为指针

[英]Converting CFSocket context to pointer

I set the context to the address of the class that created the socket like this: 我将上下文设置为创建套接字的类的地址,如下所示:

CFSocketContext ctxt = {0, (__bridge void *)(self), NULL, NULL, NULL};

    self.sock = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketDataCallBack|kCFSocketConnectCallBack, *(CFSocketCallBack)takeCallback, &ctxt);

Then in the callback I put this: 然后在回调中输入:

static void takeCallback(CFSocketRef s, CFSocketCallBackType callbackType, CFDataRef address, const void *data, void *info)
{

PUFTransCont* obj = (__bridge PUFTransCont *)(info);

}

I saw Apple sample code that does this and saw samples all over the internet doing this. 我看到了执行此操作的Apple示例代码,并看到了整个Internet上的示例。 Why is it not working when I did it. 为什么当我这样做时它不起作用。 Whenever the execution hits 每当执行命中

PUFTransCont* obj = (__bridge PUFTransCont *)(info);

I get a EXC_BAD_ACCESS 我得到一个EXC_BAD_ACCESS

Your code looks OK, but you have to ensure that the PUFTransCont object is not deallocated as long as it is used by the callback function. 您的代码看起来PUFTransCont ,但是您必须确保PUFTransCont对象不会被重新分配 ,只要它被回调函数使用即可。

One possible solution is to keep a strong reference to the object while the socket is in use (assuming that you compile with ARC). 一种可能的解决方案是在使用套接字时保持对对象的强烈引用(假设您使用ARC进行编译)。

Another possible solution is to transfer the ownership with 另一种可能的解决方案是将所有权转让给

CFSocketContext ctxt = {0, CFBridgingRetain(self), NULL, NULL, NULL};

(which increases the retain count of the object), and release it later when the object is no longer needed, for example in the callback with (这会增加对象的保留计数),然后在不再需要该对象时将其释放,例如在带有

CFRelease(info);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM